nlcc report

Human Evaluations

Follow links to add evaluation to evaluate

gaussian_input_emin

mc_harmonic

mc_ising

nwchem_input_emin

plot_3d_sin

plot_bar

plot_contour

plot_correlation

plot_dual_axis

plot_emoji

plot_outside_legend

plot_pointsize

plot_sin

plot_sin_polar

protein-render

Test Report

Global Parameters

Code Results

Test Run 0 Run 1 Run 2 Run 3 Run 4
aa_polarity Fail Fail Fail Fail Fail
adiabatic_expansion Pass Pass Pass Pass Pass
alignment Pass Pass Pass Pass Pass
angle Pass Pass Pass Pass Pass
aromatic_aa Pass Pass Pass Pass Pass
arrhenius Fail Pass Pass Fail Fail
bimolecular Pass Pass Pass Pass Pass
bb_rad Pass Pass Pass Pass Pass
blast Fail Fail Fail Fail Fail
braggant Pass Pass Pass Pass Pass
bravais Pass Pass Pass Pass Pass
canonicalize Pass Pass Pass Pass Pass
carnot_efficiency Pass Pass Pass Pass Pass
claussius Pass Pass Pass Fail Pass
compare_electronegativity Fail Fail Fail Fail Fail
condiff_1d Pass Pass Pass Pass Pass
cubes Pass Pass Pass Pass Pass
de_broglie Pass Pass Pass Pass Pass
derivative1d-ch Pass Pass Pass Pass Pass
derivative_2deg Pass Pass Pass Pass Pass
descriptors Fail Pass Pass Pass Pass
dipole Pass Pass Pass Pass Pass
dou Fail Fail Fail Fail Fail
eigen-ch Pass Pass Pass Pass Pass
eigen Pass Pass Pass Pass Pass
element_mass Fail Pass Pass Fail Fail
element_name Pass Pass Pass Pass Pass
energy_of_e Pass Pass Pass Pass Pass
find_indices Fail Fail Fail Fail Fail
force_constant Fail Fail Fail Fail Fail
fourier_1d Pass Pass Pass Pass Pass
freezing_depression Pass Pass Pass Pass Pass
genpos Fail Fail Fail Fail Fail
heating_water Fail Fail Fail Fail Fail
hydrophobic_res Fail Fail Fail Fail Fail
ideal_gas Pass Pass Pass Pass Pass
integral Fail Fail Fail Fail Fail
trap Pass Pass Pass Pass Pass
invert_matrix Pass Pass Pass Pass Pass
iupac2smiles Fail Fail Fail Fail Fail
karplusant Fail Fail Fail Fail Fail
kld Pass Pass Pass Pass Pass
langevin_dynamics Fail Fail Fail Fail Fail
weighted-least-squares Pass Fail Fail Fail Fail
lipinski_rule_of_five Pass Pass Pass Pass Pass
mape Fail Fail Fail Fail Fail
mapping_operator Fail Fail Fail Fail Fail
matpow Pass Pass Pass Pass Pass
matrix_factorial Pass Pass Pass Pass Pass
max-boltz Pass Pass Pass Pass Fail
michaelis Pass Pass Pass Pass Pass
mol_charge Fail Fail Pass Fail Fail
net_charge Pass Pass Pass Pass Pass
solve_ode Fail Fail Fail Fail Fail
ohe Fail Fail Fail Fail Fail
osmotic_pressure Pass Pass Pass Pass Pass
pair_wise Fail Fail Fail Fail Fail
pauli_matrices Pass Pass Pass Pass Pass
pi Pass Pass Pass Pass Pass
pib_1d Pass Pass Pass Pass Pass
pred_interval Pass Pass Fail Pass Pass
pubchem Fail Fail Fail Fail Fail
pyscf_energy Fail Fail Fail Fail Fail
qed Pass Fail Fail Fail Fail
quantile Fail Pass Fail Fail Fail
random_walk Fail Fail Pass Pass Pass
rank Pass Pass Pass Pass Pass
remove-water Pass Pass Pass Pass Pass
rms_velocity Pass Fail Fail Pass Fail
rmse Pass Pass Pass Pass Pass
rog Pass Pass Pass Pass Pass
rotationant Pass Pass Pass Pass Pass
rotation_higherant Pass Pass Fail Pass Fail
sasa Fail Fail Fail Pass Fail
scaffold Fail Fail Fail Fail Fail
seq-align Fail Fail Fail Fail Fail
seq-trans Pass Fail Pass Fail Pass
sequence Pass Pass Fail Pass Pass
sle Fail Fail Fail Fail Fail
spectral_r Pass Pass Pass Pass Pass
find_peaks Fail Fail Fail Fail Fail
speed_of_sound Fail Fail Fail Fail Fail
substructure Fail Fail Fail Fail Fail
tanimoto Pass Fail Pass Pass Fail
unbdistance Fail Fail Fail Fail Fail
velocity_verlet_integration Pass Pass Pass Pass Pass

Details

aa_polarity

Query

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    [insert]
    return count

Run 0

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for i in sequence:
        if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'K' or i == 'R' or i == 'H':
            count += 1
    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 1

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for i in sequence:
        if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'C' or i == 'M' or i == 'K' or i == 'R' or i == 'H':
            count += 1
    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 2

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for i in sequence:
        if i in ['R','K','N','Q','S','T','H','D','E']:
            count += 1
    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 3

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for i in sequence:
        if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
            count += 1
    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 4

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for i in sequence:
        if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'D' or i == 'E' or i == 'K' or i == 'R' or i == 'H':
            count += 1
    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

adiabatic_expansion

Query

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   [insert]
   return T2

Run 0

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

alignment

Query

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  [insert]
  return traj

Run 0

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj.superpose(traj, frame=frame_index)
  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

Success

Run 1

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj.superpose(traj, frame=frame_index)
  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

Success

Run 2

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj.superpose(traj, frame=frame_index)
  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

Success

Run 3

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj.superpose(traj, frame=frame_index)
  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

Success

Run 4

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj.superpose(traj, frame=frame_index)
  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

Success

angle

Query

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    [insert]
    return angle

Run 0

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    v1_u = v1 / np.linalg.norm(v1)
    v2_u = v2 / np.linalg.norm(v2)
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    v1_u = v1/np.linalg.norm(v1)
    v2_u = v2/np.linalg.norm(v2)
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
    if np.isnan(angle):
        if (v1_u == v2_u).all():
            return 0.0
        else:
            return np.pi
    return angle


    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    v1 = np.array(v1)
    v2 = np.array(v2)
    v1_u = v1/np.linalg.norm(v1)
    v2_u = v2/np.linalg.norm(v2)
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    v1_u = v1/np.linalg.norm(v1)
    v2_u = v2/np.linalg.norm(v2)
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
    if np.isnan(angle):
        if (v1_u == v2_u).all():
            return 0.0
        else:
            return np.pi
    return angle


    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    v1_u = v1 / np.linalg.norm(v1)
    v2_u = v2 / np.linalg.norm(v2)
    angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

aromatic_aa

Query

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    [insert]
    return count

Run 0

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for aa in sequence:
        if aa == 'F' or aa == 'Y' or aa == 'W':
            count += 1
    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 1

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for i in sequence:
        if i == "F" or i == "Y" or i == "W":
            count += 1
    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 2

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for i in sequence:
        if i == 'F' or i == 'Y' or i == 'W':
            count += 1
    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 3

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for aa in sequence:
        if aa == 'F' or aa == 'Y' or aa == 'W':
            count += 1
    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 4

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for aa in sequence:
        if aa == 'F' or aa == 'Y' or aa == 'W':
            count += 1
    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

arrhenius

Query

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   [insert]
   return k1

Run 0

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 1

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2*math.exp((-Ea*(1/T1-1/T2))/8.314)
   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 2

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2*math.exp((Ea/8.314)*((1/T2)-(1/T1)))
   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 3

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 4

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

bimolecular

Query

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   [insert]
   return rate

Run 0

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B

   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 1

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B

   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 2

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B
   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 3

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B
   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 4

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B

   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

bb_rad

Query

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   [insert]
   return B

Run 0

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.62607004e-34
   c = 299792458
   k = 1.38064852e-23
   B = 2*h*c**2/lam**5*1/(np.exp(h*c/(lam*k*T))-1)
   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34
   c = 3.0e+8
   k = 1.38e-23
   B = 2.0*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1.0)
   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.62607004e-34 # Planck's constant
   c = 299792458 # speed of light
   k = 1.38064852e-23 # Boltzmann constant
   B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.62607004e-34
   c = 299792458
   k = 1.38064852e-23
   B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.62607004e-34
   c = 299792458
   k = 1.38064852e-23
   B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

blast

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    [insert]
    return e, id

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup

    # 2. Submit BLAST search with sequences
    url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
    params = {'QUERY': seq, 'PROGRAM': 'blastp', 'DATABASE': 'swissprot', 'CMD': 'Put'}
    r = requests.post(url, data=params)

    # 3. Get result
    url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
    params = {'RID': r.text.split('\n')[-2].split('=')[-1], 'CMD': 'Get'}
    r = requests.get(url, params=params)

    # 4. Parse MSA
    soup = BeautifulSoup(r.text, 'html.parser')
    msa = soup.find('pre').text

    # 5. Return a tuple of e score, id of top match
    e = float(msa.split('\n')[1].split(' ')[-1])
    id = msa.split('\n')[2].split(' ')[1]
    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

'NoneType' object has no attribute 'text'

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup

    # 2. Submit BLAST search with sequences
    url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
    params = {'PAGE': 'Proteins',
              'PROGRAM': 'blastp',
              'DATABASE': 'nr',
              'QUERY': seq}
    r = requests.get(url, params=params)

    # 3. Get result
    soup = BeautifulSoup(r.text, 'html.parser')
    result = soup.find('pre').text

    # 4. Parse MSA
    result = result.split('\n')
    result = [line for line in result if line.startswith('>')]
    result = [line.split('|')[3] for line in result]

    # 5. Return a tuple of e score, id of top match
    e = float(result[0].split(' ')[-1])
    id = result[0].split(' ')[0]
    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

'NoneType' object has no attribute 'text'

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1.
    import requests
    from bs4 import BeautifulSoup

    # 2.
    url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
    params = {'QUERY': seq,
              'DATABASE': 'nr',
              'PROGRAM': 'blastp',
              'CMD': 'Put',
              'HITLIST_SIZE': 1}
    r = requests.get(url, params=params)

    # 3.
    soup = BeautifulSoup(r.text, 'html.parser')
    msa = soup.find_all('pre')[1].text

    # 4.
    msa = msa.split('\n')
    msa = [i.split() for i in msa]
    msa = np.array(msa)
    msa = msa[msa[:, 0] != '>', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != 'T', :]
    msa = msa[msa[:, 0] != 'Score', :]
    msa = msa[msa[:, 0] != 'Identities', :]
    msa = msa[msa[:, 0] != 'Gaps', :]
    msa = msa[msa[:, 0] != 'Strand', :]
    msa = msa[msa[:, 0] != 'Frame', :]
    msa = msa[msa[:, 0] != 'Query', :]
    msa = msa[msa[:, 0] != 'Sbjct', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :]
    msa = msa[msa[:, 0] != '', :
    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

invalid syntax (<string>, line 74)

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup

    # 2. Submit BLAST search with sequences
    r = requests.get('https://blast.ncbi.nlm.nih.gov/Blast.cgi', params={
        'QUERY': seq,
        'DATABASE': 'nr',
        'PROGRAM': 'blastp',
        'FILTER': 'L',
        'EXPECT': '10',
        'HITLIST_SIZE': '1',
        'CMD': 'Put',
        'FORMAT_TYPE': 'HTML',
        'PAGE': 'Nucleotides'
    })

    # 3. Get result
    soup = BeautifulSoup(r.text, 'html.parser')

    # 4. Parse MSA
    msa = soup.find('div', {'class': 'blastview'}).find('pre').text

    # 5. Return a tuple of e score, id of top match
    e = float(soup.find('div', {'class': 'blastview'}).find('pre').text.split('\n')[1].split()[-2])
    id = soup.find('div', {'class': 'blastview'}).find('pre').text.split('\n')[1].split()[1]

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

'NoneType' object has no attribute 'find'

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    from Bio.Blast import NCBIWWW
    from Bio import SeqIO
    from Bio.Seq import Seq
    from Bio.SeqRecord import SeqRecord
    from Bio.Alphabet import IUPAC
    import numpy as np
    import pandas as pd
    import requests
    from bs4 import BeautifulSoup

    # 2. Submit BLAST search with sequences
    result_handle = NCBIWWW.qblast("blastp", "nr", seq)

    # 3. Get result
    blast_result = result_handle.read()

    # 4. Parse MSA
    soup = BeautifulSoup(blast_result, 'html.parser')
    msa = soup.find_all('pre')[0].text

    # 5. Return a tuple of e score, id of top match
    e = float(msa.split('\n')[1].split('\t')[10])
    id = msa.split('\n')[1].split('\t')[1]
    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

Timeout

braggant

Query

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    [insert]
    return theta

Run 0

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arcsin(wavelength / (2 * d))
    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arcsin(wavelength / (2 * d))
    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arcsin(wavelength / (2 * d))
    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arcsin(wavelength/(2*d))
    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arcsin(wavelength / (2 * d))
    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

bravais

Query

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    [insert]
    return name

Run 0

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number < 3:
        name = "triclinic"
    elif group_number < 16:
        name = "monoclinic"
    elif group_number < 75:
        name = "orthorhombic"
    elif group_number < 143:
        name = "tetragonal"
    elif group_number < 168:
        name = "trigonal"
    elif group_number < 195:
        name = "hexagonal"
    elif group_number < 231:
        name = "cubic"
    else:
        name = "unknown"

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

Run 1

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number < 3:
        name = 'triclinic'
    elif group_number < 16:
        name = 'monoclinic'
    elif group_number < 75:
        name = 'orthorhombic'
    elif group_number < 143:
        name = 'tetragonal'
    elif group_number < 168:
        name = 'trigonal'
    elif group_number < 195:
        name = 'hexagonal'
    elif group_number < 231:
        name = 'cubic'
    else:
        name = 'unknown'

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

Run 2

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    name = None
    if group_number < 3:
        name = 'triclinic'
    elif group_number < 16:
        name = 'monoclinic'
    elif group_number < 75:
        name = 'orthorhombic'
    elif group_number < 143:
        name = 'tetragonal'
    elif group_number < 168:
        name = 'trigonal'
    elif group_number < 195:
        name = 'hexagonal'
    elif group_number < 231:
        name = 'cubic'
    else:
        raise ValueError('Invalid space group number')
    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

Run 3

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number < 1 or group_number > 230:
        raise ValueError("Invalid space group number")
    name = ""
    if group_number <= 2:
        name = "triclinic"
    elif group_number <= 15:
        name = "monoclinic"
    elif group_number <= 74:
        name = "orthorhombic"
    elif group_number <= 142:
        name = "tetragonal"
    elif group_number <= 167:
        name = "trigonal"
    elif group_number <= 194:
        name = "hexagonal"
    else:
        name = "cubic"
    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

Run 4

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    name = None
    if group_number in range(1, 3):
        name = "triclinic"
    elif group_number in range(3, 16):
        name = "monoclinic"
    elif group_number in range(16, 75):
        name = "orthorhombic"
    elif group_number in range(75, 143):
        name = "tetragonal"
    elif group_number in range(143, 168):
        name = "trigonal"
    elif group_number in range(168, 195):
        name = "hexagonal"
    elif group_number in range(195, 231):
        name = "cubic"
    else:
        raise ValueError("Invalid space group number")
    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

canonicalize

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    [insert]
    return canon_list

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol))
    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol))
    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol))
    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

carnot_efficiency

Query

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   [insert]
   return eps

Run 0

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = 1 - T_cold/T_hot
   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = 1 - T_cold/T_hot
   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = 1 - T_cold/T_hot
   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = 1 - (T_cold / T_hot)
   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = 1 - (T_cold / T_hot)
   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

claussius

Query

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   [insert]
   return P2

Run 0

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1*math.exp(HVap*(1/T1 - 1/T2))
   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1 * math.exp((HVap/8.314)*((1/T1)-(1/T2)))
   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

compare_electronegativity

Query

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   [insert]
   return result

Run 0

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   result = False
   if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
      result = True
   return result
result = True if compare_electronegativity("O","C") else False

Output:

'>' not supported between instances of 'method' and 'method'

Run 1

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
   return result
result = True if compare_electronegativity("O","C") else False

Output:

'>' not supported between instances of 'method' and 'method'

Run 2

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   result = False
   if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
      result = True
   return result
result = True if compare_electronegativity("O","C") else False

Output:

'>' not supported between instances of 'method' and 'method'

Run 3

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   result = False
   if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
      result = True
   return result
result = True if compare_electronegativity("O","C") else False

Output:

'>' not supported between instances of 'method' and 'method'

Run 4

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   result = False
   if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
      result = True
   return result
result = True if compare_electronegativity("O","C") else False

Output:

'>' not supported between instances of 'method' and 'method'

condiff_1d

Query

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  [insert]
  return diff

Run 0

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.zeros(len(x)-1)
  for i in range(len(x)-1):
    diff[i] = x[i+1] - x[i]
  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 1

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.zeros(x.shape[0]-1)
  for i in range(x.shape[0]-1):
    diff[i] = x[i+1] - x[i]
  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 2

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.zeros(len(x)-1)
  for i in range(len(x)-1):
    diff[i] = x[i+1] - x[i]
  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 3

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.zeros(len(x)-1)
  for i in range(len(x)-1):
    diff[i] = x[i+1] - x[i]
  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 4

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.zeros(len(x)-1)
  for i in range(len(x)-1):
    diff[i] = x[i+1] - x[i]
  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

cubes

Query

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  [insert]
  return s

Run 0

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = 0
  for i in range(1, n+1):
    s += i**3
  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 1

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = 0
  for i in range(1, n+1):
    s += i**3
  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 2

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = 0
  for i in range(1, n+1):
    s += i**3
  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 3

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = 0
  for i in range(1, n+1):
    s += i**3
  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 4

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = 0
  for i in range(1, n+1):
    s += i**3
  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

de_broglie

Query

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   [insert]
   return l

Run 0

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = (h*v)/(m*v**2)
   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 1

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = h/math.sqrt(2*m*v**2)
   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 2

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.626e-34
   l = h / (m * v)
   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 3

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = (h*v)/(m*v**2)
   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 4

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = h/(m*v)
   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

derivative1d-ch

Query

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  [insert]
  return d

Run 0

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  d = 2*a*x + b
  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 1

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  d = 2*a*x + b
  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 2

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  d = 2*a*x + b

  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 3

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  d = 2*a*x + b
  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 4

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  d = 2*a*x + b
  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

derivative_2deg

Query

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  [insert]
  return deriv

Run 0

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = 2*a*x + b
  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 1

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = 2*a*x + b
  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 2

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = 2*a*x + b
  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 3

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = 2*a*x + b
  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 4

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = 2*a*x + b
  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

descriptors

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    [insert]
    return descriptors

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        descriptors.append([
            Descriptors.MolWt(mol),
            Descriptors.ExactMolWt(mol),
            Descriptors.NumValenceElectrons(mol),
            Descriptors.NumRadicalElectrons(mol),
            Descriptors.TPSA(mol),
            Descriptors.LabuteASA(mol),
            Descriptors.NumRotatableBonds(mol),
            Descriptors.NumHDonors(mol),
            Descriptors.NumHAcceptors(mol),
            Descriptors.FractionCSP3(mol),
            Descriptors.HeavyAtomCount(mol),
            Descriptors.RingCount(mol),
            Descriptors.MolLogP(mol),
            Descriptors.MolMR(mol),
            Descriptors.BalabanJ(mol),
            Descriptors.BertzCT(mol),
            Descriptors.Ipc(mol),
            Descriptors.HallKierAlpha(mol),
            Descriptors.Kappa1(mol),
            Descriptors.Kappa2(mol),
            Descriptors.Kappa3(mol),
            Descriptors.Chi0(mol),
            Descriptors.Chi1(mol),
            Descriptors.Chi0n(mol),
            Descriptors.Chi1n(mol),
            Descriptors.Chi2n(mol),
            Descriptors.Chi3n(mol),
            Descriptors.Chi4n(mol),
            Descriptors.Chi0v(mol),
            Descriptors.Chi1v(mol),
            Descriptors.Chi2v(mol),
            Descriptors.Chi3v(mol),
            Descriptors.Chi4v(mol),
            Descriptors.MolVolume(mol),
            Descriptors.MolSurfaceArea(mol),
            Descriptors.MolFractionCSP3(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol),
            Descriptors.MolFractionSP3(mol),
            Descriptors.MolFractionSP2(mol),
            Descriptors.MolFractionSP(mol
    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

invalid syntax (<string>, line 89)

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        descriptors.append([
            Descriptors.MolWt(mol),
            Descriptors.NumHAcceptors(mol),
            Descriptors.NumHDonors(mol),
            Descriptors.NumRotatableBonds(mol),
            Descriptors.NumValenceElectrons(mol),
            Descriptors.TPSA(mol),
            Crippen.MolLogP(mol),
            Descriptors.ExactMolWt(mol)
        ])
    descriptors = np.array(descriptors)
    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        descriptors.append(np.array([
            rdMolDescriptors.CalcExactMolWt(mol),
            rdMolDescriptors.CalcTPSA(mol),
            rdMolDescriptors.CalcNumRotatableBonds(mol),
            rdMolDescriptors.CalcNumHBA(mol),
            rdMolDescriptors.CalcNumHBD(mol),
            rdMolDescriptors.CalcNumHeteroatoms(mol),
            rdMolDescriptors.CalcNumRings(mol),
            rdMolDescriptors.CalcNumAromaticRings(mol),
        ]))
    descriptors = np.array(descriptors)
    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        descriptors.append([
            Descriptors.MolLogP(mol),
            Descriptors.TPSA(mol),
            Descriptors.NumHAcceptors(mol),
            Descriptors.NumHDonors(mol),
            Descriptors.NumRotatableBonds(mol),
            Descriptors.NumAromaticRings(mol),
            Descriptors.NumSaturatedRings(mol),
            Descriptors.NumAliphaticRings(mol)
        ])
    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        descriptors.append([
            Descriptors.MolWt(mol),
            Descriptors.NumValenceElectrons(mol),
            Descriptors.NumRadicalElectrons(mol),
            Descriptors.NumHDonors(mol),
            Descriptors.NumHAcceptors(mol),
            Descriptors.TPSA(mol),
            Descriptors.LabuteASA(mol),
            Descriptors.ExactMolWt(mol)
        ])
    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

dipole

Query

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  [insert]
  return dipole_moment

Run 0

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)

  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 1

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)
  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 2

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.dot(coordinates.T, charges)
  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 3

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)
  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 4

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.zeros(3)
  for i in range(len(coordinates)):
    dipole_moment += charges[i]*coordinates[i]

  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

dou

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    [insert]
    return d

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    c = rdMolDescriptors.CalcNumAtomStereoCenters(mol)
    n = rdMolDescriptors.CalcNumAmideBonds(mol)
    h = rdMolDescriptors.CalcNumHBD(mol)
    hal = rdMolDescriptors.CalcNumHBA(mol)
    d = c + n + h + hal
    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    return rdMolDescriptors.CalcNumLipinskiHBA(mol), rdMolDescriptors.CalcNumLipinskiHBD(mol)


    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    d = Descriptors.NumRotatableBonds(mol)
    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    m = Chem.MolFromSmiles(smiles)
    d = Descriptors.NumRotatableBonds(m)
    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.NumRotatableBonds(mol)


    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

eigen-ch

Query

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    [insert]
    return w,v

Run 0

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 1

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 2

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 3

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 4

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

eigen

Query

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    [insert]
    return w,v

Run 0

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 1

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 2

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 3

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 4

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w,v = np.linalg.eig(M)
    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

element_mass

Query

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   [insert]
   return mass

Run 0

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.element(element_symbol).mass
   if mass == None:
      print "Error: element mass not found for element", element_symbol
      sys.exit(1)
   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found for element", element_symbol)? (<string>, line 12)

Run 1

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.element(element_symbol).mass
   if mass == None:
      sys.exit('Error: element '+element_symbol+' not found')
   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 2

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.element(element_symbol).mass
   if mass == None:
      print("Error: element symbol not found")
      sys.exit()
   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 3

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.element(element_symbol).mass
   if mass == None:
      print "Error: element mass not found for %s" % element_symbol
      sys.exit(1)
   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found for %s" % element_symbol)? (<string>, line 12)

Run 4

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.element(element_symbol).mass
   if mass == None:
      print "Element mass for %s not found" % element_symbol
      sys.exit(1)
   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Missing parentheses in call to 'print'. Did you mean print("Element mass for %s not found" % element_symbol)? (<string>, line 12)

element_name

Query

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  [insert]
  return s

Run 0

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.element(element_number).symbol
  return s
result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 1

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.element(element_number).symbol
  return s
result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 2

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.element(element_number).symbol
  return s
result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 3

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.element(element_number).symbol
  return s
result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 4

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.element(element_number).symbol
  return s
result = True if symbol(26).lower()=="fe" else False

Output:

Success

energy_of_e

Query

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    [insert]
    return energy

Run 0

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = -13.6*(1/n**2)
    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 1

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = -13.6*(1/n**2)
    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 2

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = -13.6*(1/n**2)
    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 3

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = -13.6/n**2
    return energy


    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 4

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = -13.6*(1/n**2)
    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

find_indices

Query

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  [insert]
  return idx

Run 0

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  idx = np.where(traj.topology.select('name CA'))[0][:2]
  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  idx = []
  for i in range(2):
    idx.append(traj.topology.select('name CA and resid %d' % (i+1)))
  idx = np.array(idx)
  idx = idx.flatten()
  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  idx = topology.select('name CA')
  idx = idx[:2]
  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  idx = np.where(traj.topology.select('name CA'))[0][:2]
  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  idx = np.where(traj.topology.select('name CA'))[0]
  idx = idx[:2]
  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

force_constant

Query

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    [insert]
    return k

Run 0

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = (1.0/2.0)*(1.0/m1 + 1.0/m2)*(1.0/wave_len)**2
    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = (m1*m2)/(m1+m2)*(wave_len*1e-2)**2*1.98644568e-23
    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = (1.0/2.0)*(m1*m2)/(m1+m2)*(wave_len*1.0e-2)**2
    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = (1.0/2.0)*((m1*m2)/(m1+m2))*(1.0/(wave_len*100.0))**2
    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = (1.99e-23*(1e2)**2)/(wave_len*(m1*m2)/(m1+m2))
    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

fourier_1d

Query

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  [insert]
  return w

Run 0

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)
  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 1

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)
  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 2

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)
  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 3

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)
  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 4

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  N = len(x)
  w = np.zeros(N, dtype=complex)
  for k in range(N):
    w[k] = np.sum(x*np.exp(-2j*np.pi*k*np.arange(N)/N))
  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

freezing_depression

Query

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   [insert]
   return deltaT

Run 0

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf*m
   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 1

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf * m
   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 2

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf*m
   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 3

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf*m
   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 4

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf*m
   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

genpos

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    [insert]
    return generators

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'https://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum={}'.format(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table')
    generators = []
    for row in table.find_all('tr'):
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([float(ele) for ele in cols])
    generators = np.array(generators)
    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

'NoneType' object has no attribute 'find_all'

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum={}'.format(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table')
    generators = []
    for row in table.findAll('tr'):
        col = row.findAll('td')
        if col:
            generators.append(np.array([[float(col[0].string), float(col[1].string), float(col[2].string)],
                                        [float(col[3].string), float(col[4].string), float(col[5].string)],
                                        [float(col[6].string), float(col[7].string), float(col[8].string)]]))
    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

'NoneType' object has no attribute 'findAll'

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table')
    generators = []
    for row in table.find_all('tr'):
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([float(ele) for ele in cols])
    generators = np.array(generators)
    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

'NoneType' object has no attribute 'find_all'

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find_all('table')[0]
    generators = []
    for row in table.find_all('tr'):
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([float(ele) for ele in cols])
    generators = np.array(generators)
    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    generators = []
    for i in range(3):
        generators.append(np.array([[float(x) for x in soup.find_all('tr')[i+1].find_all('td')[1].text.split()],
                                    [float(x) for x in soup.find_all('tr')[i+1].find_all('td')[2].text.split()],
                                    [float(x) for x in soup.find_all('tr')[i+1].find_all('td')[3].text.split()]]))
    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

heating_water

Query

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   [insert]
   return q

Run 0

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n*4.184*(T2-T1)
   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * 4.184 * (T2 - T1)
   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * 4.184 * (T2 - T1)
   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * 4.184 * (T2 - T1)
   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * (T2 - T1) * 4.184
   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

hydrophobic_res

Query

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  [insert]
  return resids

Run 0

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  t = md.load(pdb_filename)
  resids = []
  for i in range(t.n_residues):
    if t.top.residue(i).is_hydrophobic:
      resids.append(i)
  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Residue' object has no attribute 'is_hydrophobic'

Run 1

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  traj = md.load(pdb_filename)
  resids = []
  for atom in traj.topology.atoms:
    if atom.residue.is_water:
      continue
    if atom.element.symbol == 'C':
      resids.append(atom.residue.index)
  resids = np.array(resids)
  resids = np.unique(resids)
  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

Success

Run 2

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  traj = md.load(pdb_filename)
  resids = []
  for i in range(traj.n_residues):
    if traj.topology.residue(i).is_hydrophobic:
      resids.append(i)
  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Residue' object has no attribute 'is_hydrophobic'

Run 3

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  traj = md.load(pdb_filename)
  resids = []
  for i in range(traj.n_residues):
    if traj.topology.residue(i).is_hydrophobic:
      resids.append(i)
  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Residue' object has no attribute 'is_hydrophobic'

Run 4

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  t = md.load(pdb_filename)
  resids = []
  for i in range(t.n_residues):
    if t.top.residue(i).is_hydrophobic:
      resids.append(i)
  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Residue' object has no attribute 'is_hydrophobic'

ideal_gas

Query

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   [insert]
   return P

Run 0

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm*L/(mol*K)
   P = (n*R*T)/V
   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.0821 # atm L / mol K
   P = (n * R * T) / V
   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.0821 # atm*L/mol*K
   P = (n*R*T)/V
   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.0821 # atm L / mol K
   P = (n * R * T) / V
   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm L mol-1 K-1
   P = (n*R*T)/V
   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

integral

Query

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  [insert]
  return integral

Run 0

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = a*(b**2)/2 + b*c + c*d + d**2/2
  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 1

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 2

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = a*(b**2)/2 + b*c + c*d + d**2/2
  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 3

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b

  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 4

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

trap

Query

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  [insert]
  return integral

Run 0

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  integral = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    integral += f(a+i*h)
  integral *= h
  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 1

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  integral = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    integral += f(a + i*h)
  integral *= h
  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 2

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  integral = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    integral += f(a+i*h)
  integral *= h
  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 3

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  integral = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    integral += f(a+i*h)
  integral *= h
  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 4

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  x = np.linspace(a, b, n+1)
  h = (b-a)/n
  integral = 0.5*h*(f(x[0]) + f(x[-1]))
  for i in range(1, n):
    integral += h*f(x[i])

  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

invert_matrix

Query

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    [insert]
    return Ainv

Run 0

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    Ainv = np.linalg.inv(A)
    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 1

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    Ainv = np.linalg.inv(A)
    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 2

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    Ainv = np.linalg.inv(A)
    
    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 3

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    Ainv = np.linalg.inv(A)
    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 4

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    Ainv = np.linalg.inv(A)
    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

iupac2smiles

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    [insert]
    return SMILES

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(IUPAC)
    SMILES = Chem.MolToSmiles(mol)
    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Python argument types in
    rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
    MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
    SMILES = Chem.MolToSmiles(mol)
    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Python argument types in
    rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
    MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    m = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
    SMILES = Chem.MolToSmiles(m)
    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Python argument types in
    rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
    MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

karplusant

Query

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    [insert]
    return J

Run 0

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = np.cos(phi) * A + np.sin(phi) * B + C
    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = np.cos(phi) * A - np.sin(phi) * B + C
    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = (A*np.cos(phi)**2 + B*np.sin(phi)**2 + C*np.sin(phi)*np.cos(phi))/2
    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = (A * np.cos(phi)**2 + B * np.sin(phi)**2 + C * np.sin(phi) * np.cos(phi)) / 2
    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = (A * np.cos(phi)**2 + B * np.sin(phi)**2 + C * np.sin(phi) * np.cos(phi)) / 2

    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

kld

Query

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  [insert]
  return loss

Run 0

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 1

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 2

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 3

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 4

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

langevin_dynamics

Query

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    [insert]
    return x_traj, v_traj

Run 0

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt - (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
        x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt

    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 1

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2/m
        v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i])/m + F(x_traj[i+1])/m)*dt
        v_traj[i+1] += np.sqrt(2*gamma*T*dt)*np.random.normal()
        v_traj[i+1] /= (1+gamma*dt)

    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 2

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
        x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 3

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1,n_steps):
        v_traj[i] = v_traj[i-1] - (gamma/m)*v_traj[i-1]*dt - (F(x_traj[i-1])/m)*dt + np.sqrt(2*gamma*T/m)*np.random.normal(0,1)*np.sqrt(dt)
        x_traj[i] = x_traj[i-1] + v_traj[i]*dt

    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 4

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        x_traj[i+1] = x_traj[i] + dt*v_traj[i]
        v_traj[i+1] = v_traj[i] - dt*gamma*v_traj[i] - dt*F(x_traj[i]) + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

weighted-least-squares

Query

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    [insert]
    return beta

Run 0

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

Success

Run 1

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    x = np.matrix(x)
    y = np.matrix(y)
    w = np.matrix(w)
    beta = (x.T * w * x).I * x.T * w * y
    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)

Run 2

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.inv(x.T @ w @ x) @ x.T @ w @ y
    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 100 is different from 3)

Run 3

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    x = np.matrix(x)
    y = np.matrix(y)
    w = np.matrix(w)
    beta = np.linalg.inv(x.T*w*x)*x.T*w*y
    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)

Run 4

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    x = np.matrix(x)
    y = np.matrix(y)
    w = np.matrix(w)
    beta = (x.T * w * x).I * x.T * w * y
    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)

lipinski_rule_of_five

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    [insert]
    return result

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    result = True
    if rdMolDescriptors.CalcNumHBD(mol) > 5:
        result = False
    if rdMolDescriptors.CalcNumHBA(mol) > 10:
        result = False
    if Descriptors.MolWt(mol) > 500:
        result = False
    if Crippen.MolLogP(mol) > 5:
        result = False
    return result


    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    hbd = rdMolDescriptors.CalcNumHBD(mol)
    hba = rdMolDescriptors.CalcNumHBA(mol)
    mw = Descriptors.MolWt(mol)
    logp = Crippen.MolLogP(mol)
    result = True
    if hbd > 5:
        result = False
    if hba > 10:
        result = False
    if mw > 500:
        result = False
    if logp > 5:
        result = False
    return result


    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    result = True
    if rdMolDescriptors.CalcNumHBD(mol) > 5:
        result = False
    if rdMolDescriptors.CalcNumHBA(mol) > 10:
        result = False
    if Descriptors.MolWt(mol) > 500:
        result = False
    if Crippen.MolLogP(mol) > 5:
        result = False

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    m = Chem.MolFromSmiles(smiles)
    num_hbd = rdMolDescriptors.CalcNumHBD(m)
    num_hba = rdMolDescriptors.CalcNumHBA(m)
    mw = Descriptors.MolWt(m)
    logp = Crippen.MolLogP(m)
    result = num_hbd <= 5 and num_hba <= 10 and mw < 500 and logp < 5
    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    result = True
    if rdMolDescriptors.CalcNumHBD(mol) > 5:
        result = False
    if rdMolDescriptors.CalcNumHBA(mol) > 10:
        result = False
    if Descriptors.MolWt(mol) > 500:
        result = False
    if Crippen.MolLogP(mol) > 5:
        result = False

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

mape

Query

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  [insert]
  return e

Run 0

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y)):
    e += abs(y_hat[i]-y[i])/y[i]
  e = e/len(y)
  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

Run 1

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y)):
    e += abs((y_hat[i]-y[i])/y[i])
  e = e/len(y)
  return e


  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

Run 2

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y_hat)):
    e += abs((y_hat[i]-y[i])/y[i])
  e = e/len(y_hat)
  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

Run 3

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y)):
    e += abs(y_hat[i] - y[i]) / y[i]
  e /= len(y)
  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

Run 4

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y)):
    e += abs(y_hat[i]-y[i])/y[i]
  e /= len(y)
  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

mapping_operator

Query

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  [insert]
  return M

Run 0

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((molecule.atoms.n_atoms, len(beads_mappings)))
  for i, beads in enumerate(beads_mappings):
    M[beads.indices, i] = 1.0

  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'indices'

Run 1

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((molecule.n_atoms, len(beads_mappings)))
  for i, bead in enumerate(beads_mappings):
    M[bead.indices, i] = bead.masses / bead.masses.sum()
  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'masses'

Run 2

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((len(molecule.atoms), len(beads_mappings)))
  for i, beads in enumerate(beads_mappings):
    M[beads.indices, i] = beads.masses

  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'masses'

Run 3

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((molecule.n_atoms, len(beads_mappings)))
  for i, beads_selection in enumerate(beads_mappings):
    M[beads_selection.indices, i] = beads_selection.masses/beads_selection.masses.sum()
  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'masses'

Run 4

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((len(beads_mappings), molecule.n_atoms))
  for i, bead in enumerate(beads_mappings):
    M[i, bead.indices] = bead.masses / bead.masses.sum()

  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'masses'

matpow

Query

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  [insert]
  return r

Run 0

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.eye(x.shape[0])
  for i in range(n):
    r = np.dot(r,x)
  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 1

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.eye(x.shape[0])
  for i in range(n):
    r = np.dot(r,x)
  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 2

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.eye(x.shape[0])
  for i in range(n):
    r = np.dot(r,x)
  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 3

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.eye(x.shape[0])
  for i in range(n):
    r = r.dot(x)
  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 4

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.eye(x.shape[0])
  for i in range(n):
    r = r.dot(x)
  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

matrix_factorial

Query

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     [insert]
     return f

Run 0

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.zeros(n.shape)
     for i in range(n.shape[0]):
          for j in range(n.shape[1]):
               f[i,j] = np.math.factorial(n[i,j])
     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

Run 1

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.zeros(n.shape)
     for i in range(n.shape[0]):
          for j in range(n.shape[1]):
               f[i,j] = np.math.factorial(n[i,j])
     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

Run 2

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.zeros(n.shape)
     for i in range(n.shape[0]):
          for j in range(n.shape[1]):
               f[i,j] = np.math.factorial(n[i,j])
     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

Run 3

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.zeros(n.shape)
     for i in range(n.shape[0]):
          for j in range(n.shape[1]):
               f[i,j] = np.math.factorial(n[i,j])

     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

Run 4

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.ones(n.shape)
     for i in range(n.shape[0]):
          for j in range(n.shape[1]):
               f[i,j] = np.math.factorial(n[i,j])
     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

max-boltz

Query

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   [insert]
   return s

Run 0

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806488e-23
   s = math.sqrt(3*k*T/M)
   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806e-23
   s = math.sqrt(3*k*T/M)
   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.38064852e-23
   s = math.sqrt(3*k*T/M)
   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806488e-23
   s = math.sqrt(3*k*T/M)
   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806488e-23
   s = math.sqrt(3*k*T/M)
   print "The rms speed is %.2f m/s" % s
   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Missing parentheses in call to 'print'. Did you mean print("The rms speed is %.2f m/s" % s)? (<string>, line 14)

michaelis

Query

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   [insert]
   return v

Run 0

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * S / (Km + S)
   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * S / (Km + S)
   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax*S/(Km+S)
   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax*S/(Km+S)
   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = (Vmax * S) / (Km + S)
   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

mol_charge

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    [insert]
    return charge

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Descriptors.MolLogP(mol)
    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = rdMolDescriptors.CalcFormalCharge(mol)
    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

module 'rdkit.Chem.rdMolDescriptors' has no attribute 'CalcFormalCharge'

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = 0
    for atom in mol.GetAtoms():
        charge += atom.GetFormalCharge()
    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Descriptors.MolWt(mol)
    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = rdMolDescriptors.CalcFormalCharge(mol)
    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

module 'rdkit.Chem.rdMolDescriptors' has no attribute 'CalcFormalCharge'

net_charge

Query

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    [insert]
    return charge

Run 0

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for i in sequence:
        if i == 'R' or i == 'K':
            charge += 1
        elif i == 'D' or i == 'E':
            charge -= 1
    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 1

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for amino_acid in sequence:
        if amino_acid == 'R' or amino_acid == 'K':
            charge += 1
        elif amino_acid == 'D' or amino_acid == 'E':
            charge -= 1
    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 2

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for i in sequence:
        if i == 'K' or i == 'R':
            charge += 1
        elif i == 'D' or i == 'E':
            charge -= 1
        else:
            charge += 0
    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 3

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for aa in sequence:
        if aa == 'R' or aa == 'K':
            charge += 1
        elif aa == 'D' or aa == 'E':
            charge -= 1
        else:
            charge += 0

    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 4

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for i in sequence:
        if i == 'K' or i == 'R':
            charge += 1
        elif i == 'D' or i == 'E':
            charge -= 1
        else:
            charge += 0

    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

solve_ode

Query

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    [insert]
    return sol

Run 0

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = h * fn(t[i], y[i])
        k2 = h * fn(t[i] + h/4, y[i] + k1/4)
        k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    sol = y
    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = h*fn(t[i], y[i])
        k2 = h*fn(t[i] + h/4, y[i] + k1/4)
        k3 = h*fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
        k4 = h*fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h*fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h*fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    sol = y
    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 2

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = np.zeros((len(t), len(y0)))
    sol[0] = y0
    for i in range(len(t)-1):
        h = t[i+1] - t[i]
        k1 = fn(t[i], sol[i])
        k2 = fn(t[i] + h/4, sol[i] + h*k1/4)
        k3 = fn(t[i] + 3*h/8, sol[i] + 3*h*k1/32 + 9*h*k2/32)
        k4 = fn(t[i] + 12*h/13, sol[i] + 1932*h*k1/2197 - 7200*h*k2/2197 + 7296*h*k3/2197)
        k5 = fn(t[i] + h, sol[i] + 439*h*k1/216 - 8*h*k2 + 3680*h*k3/513 - 845*h*k4/4104)
        k6 = fn(t[i] + h/2, sol[i] - 8*h*k1/27 + 2*h*k2 - 3544*h*k3/2565 + 1859*h*k4/4104 - 11*h*k5/40)
        sol[i+1] = sol[i] + h*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)

    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = h * fn(t[i], y[i])
        k2 = h * fn(t[i] + h/4, y[i] + k1/4)
        k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    sol = y
    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0
    for i in range(n-1):
        dt = t[i+1] - t[i]
        k1 = fn(t[i], y[i])
        k2 = fn(t[i] + dt/4, y[i] + dt*k1/4)
        k3 = fn(t[i] + 3*dt/8, y[i] + 3*dt*(k1 + k2)/32)
        k4 = fn(t[i] + 12*dt/13, y[i] + 1932*dt*(-k1 + 7*k2 + 12*k3)/2197)
        k5 = fn(t[i] + dt, y[i] + 439*dt*(-8*k1 + 36*k2 - 36*k3 + 16*k4)/216)
        k6 = fn(t[i] + dt/2, y[i] + 845*dt*(k1 - 8*k2 + 13*k3 - 13*k4 + 9*k5)/216)
        y[i+1] = y[i] + dt*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
    sol = y
    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

ohe

Query

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  [insert]
  return v

Run 0

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros((len(a), len(a)))
  for i in range(len(a)):
    v[i, i] = 1
  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

operands could not be broadcast together with shapes (10,10) (10,5) 

Run 1

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros((len(a), len(set(a))))
  for i, k in enumerate(a):
    v[i, k] = 1
  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Run 2

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros((len(a), len(a)))
  for i in range(len(a)):
    v[i, i] = 1
  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

operands could not be broadcast together with shapes (10,10) (10,5) 

Run 3

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros((len(a), len(set(a))))
  for i, k in enumerate(a):
    v[i, k] = 1
  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Run 4

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros((len(a), len(a)))
  for i in range(len(a)):
    v[i, i] = 1
  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

operands could not be broadcast together with shapes (10,10) (10,5) 

osmotic_pressure

Query

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   [insert]
   return p

Run 0

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = Pi/(R*T)
   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 1

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = Pi/(R*T)
   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 2

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = Pi/R/T
   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 3

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = Pi/(R*T)
   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 4

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = Pi/(R*T)
   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

pair_wise

Query

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  [insert]
  return distances

Run 0

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  traj = md.load(pdb_file)
  alpha_carbons = traj.topology.select('name CA')
  distances = md.compute_distances(traj, alpha_carbons, periodic=False)
  distances = np.tril(distances)
  distances = distances[distances > 0]
  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  traj = md.load(pdb_file)
  alpha_carbons = traj.topology.select('name CA')
  distances = md.compute_distances(traj, alpha_carbons, periodic=False)
  distances = distances[0]
  distances = np.triu(distances)
  distances = distances[np.nonzero(distances)]
  distances = distances.reshape(len(distances),1)
  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  alpha_carbons = topology.select('name CA')
  distances = md.compute_distances(traj, alpha_carbons, periodic=False)
  distances = distances[0]
  distances = np.triu(distances)
  distances = distances[distances != 0]
  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  alpha_carbons = topology.select('name CA')
  distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
  distances = distances[np.triu_indices(len(alpha_carbons), k=1)]
  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  alpha_carbons = topology.select('name CA')
  distances = md.compute_distances(traj, alpha_carbons, periodic=False)
  distances = np.triu(distances)
  distances = distances[np.nonzero(distances)]
  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

pauli_matrices

Query

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    [insert]
    return sigma_x, sigma_y, sigma_z

Run 0

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 1

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 2

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 3

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 4

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

pi

Query

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    [insert]
    return pi_est

Run 0

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(0,1,nsamples)
    y = np.random.uniform(0,1,nsamples)
    r = x**2 + y**2
    pi_est = 4*np.sum(r<1)/nsamples
    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 1

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(0,1,nsamples)
    y = np.random.uniform(0,1,nsamples)
    r = np.sqrt(x**2 + y**2)
    pi_est = 4 * np.sum(r<1)/nsamples
    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 2

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(size=nsamples)
    y = np.random.uniform(size=nsamples)
    r = np.sqrt(x**2 + y**2)
    pi_est = 4.0*np.sum(r<1)/nsamples
    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 3

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(0,1,nsamples)
    y = np.random.uniform(0,1,nsamples)
    pi_est = 4*np.sum(x**2 + y**2 < 1)/nsamples
    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 4

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(low=-1.0, high=1.0, size=nsamples)
    y = np.random.uniform(low=-1.0, high=1.0, size=nsamples)
    r = x**2 + y**2
    pi_est = 4.0 * np.sum(r < 1.0) / nsamples
    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

pib_1d

Query

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   [insert]
   return e

Run 0

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 1

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 2

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 3

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 4

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

pred_interval

Query

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   [insert]
   return n

Run 0

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = np.ceil(np.log(1-pred_level)/np.log(1-p))
   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 1

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = np.ceil(np.log(1-pred_level)/np.log(1-p))
   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 2

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = 0
   while np.prod(1-p*(1-p)**np.arange(n)) < pred_level:
      n += 1
   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 3

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = np.ceil(np.log(1 - pred_level) / np.log(1 - p))
   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 4

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = np.ceil(np.log(1-pred_level)/np.log(1-p))
   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

pubchem

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  [insert]
  return mols

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  mols = set()
  payload = {'smiles': smiles, 'threshold': 80}
  r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity', params=payload)
  if r.status_code == 200:
    for cid in r.json()['IdentifierList']['CID']:
      r2 = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/JSON'.format(cid))
      if r2.status_code == 200:
        mols.add(r2.json()['PropertyTable']['Properties'][0]['CanonicalSMILES'])
  return mols


  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/' + smiles + '/cids/TXT?Threshold=80'
  response = requests.get(url)
  cids = response.text.split('\n')
  cids = [cid for cid in cids if cid != '']
  mols = []
  for cid in cids:
    url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/' + cid + '/property/CanonicalSMILES/TXT'
    response = requests.get(url)
    mols.append(response.text)
  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT".format(smiles)
  response = requests.get(url)
  cids = response.text.split()
  mols = set()
  for cid in cids:
    url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
    response = requests.get(url)
    mols.add(response.text)
  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

('Connection aborted.', TimeoutError('Timeout'))

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  # TODO: add error handling
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT".format(smiles)
  response = requests.get(url)
  cids = response.text.split()
  cids = [int(cid) for cid in cids]
  mols = []
  for cid in cids:
    url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
    response = requests.get(url)
    mols.append(response.text)
  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

invalid literal for int() with base 10: 'Status:'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  # Get the CID of the input molecule
  r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles)
  cid = r.text.split()[0]

  # Get the SMILES strings of molecules similar to the input molecule
  r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/similarity/XML' % cid)
  mols = set()
  for mol in r.text.split('\n'):
    if 'Similarity' in mol:
      mols.add(mol.split('"')[1])

  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

pyscf_energy

Query

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    [insert]
    return ground_energy

Run 0

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.Mole()
    mol.atom = atom
    mol.basis = basis
    mol.build()
    mf = pyscf.scf.RHF(mol)
    mf.kernel()
    ground_energy = mf.e_tot
    return ground_energy


    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 1

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.Mole()
    mol.atom = atom
    mol.basis = basis
    mol.build()
    mf = pyscf.scf.RHF(mol)
    mf.kernel()
    ground_energy = mf.energy_tot()
    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 2

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mol.build()
    mf = pyscf.scf.RHF(mol)
    mf.scf()
    ground_energy = mf.e_tot
    return ground_energy


    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 3

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mf = pyscf.scf.RHF(mol)
    mf.kernel()
    ground_energy = mf.e_tot
    print("Ground state energy:",ground_energy)
    return ground_energy


    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 4

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mf = pyscf.scf.RHF(mol)
    mf.scf()
    ground_energy = mf.e_tot

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

qed

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    [insert]
    return result

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    result = Descriptors.qed(mol)
    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    result = Crippen.MolLogP(mol)
    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    result = Crippen.MolLogP(mol)
    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    result = Crippen.MolLogP(mol)
    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    qed = Crippen.MolLogP(mol)
    return qed


    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

quantile

Query

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  [insert]
  return result

Run 0

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  a = np.asarray(a)
  if q == 0:
    result = np.min(a)
  elif q == 1:
    result = np.max(a)
  else:
    result = np.percentile(a, q*100)
  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

operands could not be broadcast together with shapes (300,) (3,) 

Run 1

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  a = np.array(a)
  result = np.empty(len(q))
  for i, qi in enumerate(q):
    result[i] = np.percentile(a, qi*100)
  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

Success

Run 2

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  a = np.sort(a)
  n = len(a)
  if isinstance(q, np.ndarray):
    result = np.zeros(len(q))
    for i in range(len(q)):
      result[i] = a[int(np.floor(q[i] * n))]
  else:
    result = a[int(np.floor(q * n))]
  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

only size-1 arrays can be converted to Python scalars

Run 3

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.percentile(a, q*100)
  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

operands could not be broadcast together with shapes (300,) (3,) 

Run 4

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  a = np.asarray(a)
  if np.isscalar(q):
    q = [q]
  q = np.asarray(q)
  if np.any((q < 0) | (q > 1)):
    raise ValueError('Quantiles must be between 0 and 1 inclusive.')
  result = np.empty(q.shape)
  m = a.size
  n = (m - 1) * q + 1
  n_lo = np.floor(n).astype(int)
  n_hi = np.ceil(n).astype(int)
  for i, (n_l, n_h) in enumerate(zip(n_lo, n_hi)):
    if n_l == 0:
      result[i] = a[0]
    elif n_h == m:
      result[i] = a[m - 1]
    else:
      result[i] = a[n_l - 1] + (n[i] - n_l) * (a[n_h - 1] - a[n_l - 1])
  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

Success

random_walk

Query

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    [insert]
    return traj

Run 0

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = np.zeros(N)
    for i in range(N):
        traj[i] = x0
        x0 += a*np.random.choice([-1,1])
    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Timeout

Run 1

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = np.zeros(N)
    for i in range(N):
        traj[i] = x0 + a*np.random.choice([-1,1])
        x0 = traj[i]
    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Timeout

Run 2

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = np.zeros(N)
    for i in range(N):
        traj[i] = x0
        x0 += a*(np.random.randint(2)*2-1)
    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

Run 3

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = np.zeros(N)
    for i in range(N):
        if np.random.rand() < 0.5:
            traj[i] = x0 + a
        else:
            traj[i] = x0 - a
        x0 = traj[i]
    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

Run 4

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = np.zeros(N)
    for i in range(N):
        traj[i] = x0
        x0 += a*(np.random.randint(2)*2-1)
    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

rank

Query

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    [insert]
    return r

Run 0

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    r = np.sum(s > 1e-12)
    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 1

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    r = np.sum(s > 1e-12)
    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 2

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, S, V = np.linalg.svd(M)
    r = np.sum(S > 1e-15)
    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 3

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    r = np.sum(s > 1e-12)
    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 4

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    r = np.sum(s > 1e-12)
    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

remove-water

Query

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  [insert]
  return new_traj

Run 0

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  new_traj = traj.atom_slice(traj.topology.select('not water'))
  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 1

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  top = traj.topology
  new_traj = traj.atom_slice(top.select('not water'))
  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 2

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  top = traj.topology
  new_traj = traj.atom_slice(top.select('not water'))
  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 3

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  new_traj = traj.atom_slice(traj.top.select('not water'))
  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 4

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  top = traj.top
  new_traj = traj.atom_slice(top.select('not water'))
  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

rms_velocity

Query

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   [insert]
   return v_rms

Run 0

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23 # Boltzmann constant in J/K
   m = m*1.6605e-27 # mass in kg
   v_rms = math.sqrt(3*k*T/m)
   print(v_rms)
   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23 #J/K
   m = m*1.66054e-24 #g to amu
   v_rms = math.sqrt(3*k*T/m)
   print("The rms velocity is %.2e cm/s" % v_rms)
   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23
   v_rms = math.sqrt(3*k*T/m)
   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23
   m = m*1.6605e-27
   v_rms = math.sqrt((3*k*T)/m)
   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23
   m = m*1.66054e-24
   v_rms = math.sqrt(3*k*T/m)
   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

rmse

Query

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  [insert]
  return e

Run 0

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt(np.mean((a-b)**2))
  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 1

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt(np.mean((a-b)**2))
  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 2

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt(np.mean((a-b)**2))
  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 3

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt(np.mean((a-b)**2))
  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 4

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt(np.mean((a-b)**2))
  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

rog

Query

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  [insert]
  return rg

Run 0

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  traj = md.load(pdb_file)
  rg = md.compute_rg(traj)
  rg = np.mean(rg)

  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 1

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  # Load the pdb
  traj = md.load(pdb_file)
  # Calculate the radius of gyration
  rg = md.compute_rg(traj)
  # Return the radius of gyration
  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 2

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  traj = md.load(pdb_file)
  rg = md.compute_rg(traj)
  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 3

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  traj = md.load(pdb_file)
  rg = md.compute_rg(traj)
  rg = np.mean(rg)
  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 4

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  traj = md.load(pdb_file)
  rg = md.compute_rg(traj)
  rg = np.mean(rg)
  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

rotationant

Query

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    [insert]
    return E_rot

Run 0

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J*(J+1)
    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J*(J+1)
    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J*(J+1)
    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J*(J+1)
    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J*(J+1)
    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

rotation_higherant

Query

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    [insert]
    return E_rot

Run 0

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*(J+1) - D*J*(J+1)*(J*(J+1))
    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*(J+1) - D*J*(J+1)*(J*(J+1))
    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)/(2*B)
    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*(J+1) - D*J*(J+1)*(J*(J+1))
    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)/(2*B)
    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

sasa

Query

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  [insert]
  return sasa

Run 0

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  traj = md.load(pdb_file)
  sasa = md.shrake_rupley(traj)
  sasa = np.sum(sasa, axis=1)
  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 1

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  traj = md.load(pdb_file)
  sasa = md.shrake_rupley(traj)
  sasa = np.mean(sasa, axis=0)
  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 2

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  traj = md.load(pdb_file)
  sasa = md.shrake_rupley(traj)
  sasa = np.sum(sasa, axis=1)
  sasa = np.sum(sasa, axis=1)
  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

axis 1 is out of bounds for array of dimension 1

Run 3

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  traj = md.load(pdb_file)
  sasa = md.shrake_rupley(traj, mode='residue')
  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 4

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  traj = md.load(pdb_file)
  sasa = md.shrake_rupley(traj, mode='residue')
  sasa = np.sum(sasa, axis=1)
  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

scaffold

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    [insert]
    return scaffold_smiles

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(Chem.MolFromSmiles(smiles))
    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'

seq-align

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    [insert]
    return aligned

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    aligned = alns[0][0]
    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    aligned = pairwise2.format_alignment(*alns[0])
    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    aligned = pairwise2.format_alignment(*alns[0])
    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    aligned = pairwise2.format_alignment(*alns[0])
    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    aligned = pairwise2.format_alignment(*alns[0])
    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

seq-trans

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  [insert]
  return prot_seq

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq).translate()
  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = gene_seq.translate()
  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

translate() takes exactly one argument (0 given)

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq).translate()
  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = gene_seq.translate()
  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

translate() takes exactly one argument (0 given)

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq).translate()
  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

sequence

Query

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    [insert]
    return x

Run 0

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    x = np.logspace(np.log10(s), np.log10(e), l)
    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 1

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    x = np.logspace(np.log10(s),np.log10(e),l)
    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 2

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    x = np.array(range(l))
    x = s*(e/s)**(x/l)
    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 3

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    x = np.logspace(np.log10(s),np.log10(e),l)
    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 4

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    x = np.geomspace(s,e,l)
    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

sle

Query

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  [insert]
  return x

Run 0

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.solve(eqns)
  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 1

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.solve(eqns)
  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 2

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.solve(eqns)
  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 3

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.solve(eqns)
  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 4

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.solve(eqns)
  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

spectral_r

Query

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  [insert]
  return sradius

Run 0

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  eigenvalues = np.linalg.eigvals(a)
  sradius = np.max(np.abs(eigenvalues))
  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 1

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  eigvals = np.linalg.eigvals(a)
  sradius = max(abs(eigvals))
  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 2

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  eigval = np.linalg.eigvals(a)
  sradius = np.max(np.abs(eigval))
  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 3

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  eigenvalues = np.linalg.eigvals(a)
  sradius = np.max(np.abs(eigenvalues))
  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 4

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.max(np.abs(np.linalg.eigvals(a)))
  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

find_peaks

Query

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    [insert]
    return wavenumbers

Run 0

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
    peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
    wavenumbers = abs_spectrum[peaks, 0][:npeaks]
    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 1

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    wavenumbers = []
    for i in range(npeaks):
        max_index = np.argmax(abs_spectrum[:,1])
        wavenumbers.append(abs_spectrum[max_index,0])
        abs_spectrum[max_index,1] = 0
    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 2

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    wavenumbers = []
    for i in range(npeaks):
        peak_index = np.argmax(abs_spectrum[:, 1])
        peak_wavenumber = abs_spectrum[peak_index, 0]
        wavenumbers.append(peak_wavenumber)
        abs_spectrum[peak_index, 1] = 0

    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 3

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    wavenumbers = []
    for i in range(npeaks):
        max_idx = np.argmax(abs_spectrum[:, 1])
        wavenumbers.append(abs_spectrum[max_idx, 0])
        abs_spectrum[max_idx, 1] = 0
    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 4

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)[0]
    peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
    peaks = peaks[:npeaks]
    wavenumbers = abs_spectrum[peaks, 0]
    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

speed_of_sound

Query

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   [insert]
   return s

Run 0

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 #J/mol/K
   s = math.sqrt(gamma*R*T/m)
   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 #J/mol/K
   s = math.sqrt(gamma*R*T/m)
   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 #J/mol/K
   s = math.sqrt(gamma*R*T/m)
   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R=8.314
   s=math.sqrt(gamma*R*T/m)
   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314
   s = math.sqrt(gamma*R*T/m)
   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

substructure

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    [insert]
    return idx

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    idx = []
    for i in range(len(mol_list)):
        if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
            idx.append(i)
    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    idx = []
    for i, mol in enumerate(mol_list):
        if mol.HasSubstructMatch(Chem.MolFromSmiles(smiles)):
            idx.append(i)
    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    idx = []
    for i in range(len(mol_list)):
        if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
            idx.append(i)
    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    idx = []
    for i in range(len(mol_list)):
        if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
            idx.append(i)
    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    idx = []
    for i in range(len(mol_list)):
        if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
            idx.append(i)
    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

tanimoto

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  [insert]
  return s

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  mols = [Chem.MolFromSmiles(s) for s in smiles_list]
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
  tanimoto_matrix = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix


  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  mols = [Chem.MolFromSmiles(s) for s in smiles_list]
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
  s = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(i+1, len(fps)):
      s[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
      s[j, i] = s[i, j]
  return s


  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
  s = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      s[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
  tanimoto_matrix = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix


  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  fps = [rdMolHash.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smiles), 2, nBits=bits) for smiles in smiles_list]
  s = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(i, len(fps)):
      s[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
      s[j, i] = s[i, j]
  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.rdMolHash' has no attribute 'GetMorganFingerprintAsBitVect'

unbdistance

Query

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    [insert]
    return result

Run 0

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    #get the index of the ligand
    lig_ind = traj.topology.select('resname '+lig_str)
    #get the index of the protein
    prot_ind = traj.topology.select('protein')
    #calculate the center of mass of the ligand
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    #calculate the center of mass of the protein
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    #calculate the distance between the two
    result = md.compute_distances(traj,[lig_com,prot_com],periodic=False)
    #return the distance
    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_ind = traj.topology.select('resname ' + lig_str)
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
    result = np.sqrt(np.sum((lig_com - prot_com)**2, axis=1))
    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_ind = traj.topology.select('resname '+lig_str)
    prot_ind = traj.topology.select('not resname '+lig_str)
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    result = np.linalg.norm(lig_com-prot_com,axis=1)
    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig = traj.topology.select('resname '+lig_str)
    protein = traj.topology.select('protein')
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig))
    protein_com = md.compute_center_of_mass(traj.atom_slice(protein))
    result = np.linalg.norm(lig_com-protein_com,axis=1)
    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_ind = traj.topology.select('resname '+lig_str)
    prot_ind = traj.topology.select('protein')
    result = md.compute_distances(traj,np.array([[0,0]]),
                                  np.array([[1,lig_ind[0]]]),
                                  periodic=False)
    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

velocity_verlet_integration

Query

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    [insert]
    return x_traj, v_traj

Run 0

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i] * dt + F(x_traj[i]) * dt**2 / 2
        v_traj[i+1] = v_traj[i] + (F(x_traj[i]) + F(x_traj[i+1])) * dt / 2
    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 1

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
        v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt

    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 2

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v_traj[i+1] = v_traj[i] + 0.5*dt*F(x_traj[i])
        x_traj[i+1] = x_traj[i] + dt*v_traj[i+1]
        v_traj[i+1] = v_traj[i+1] + 0.5*dt*F(x_traj[i+1])
    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 3

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + v_traj[i-1] * dt + 0.5 * F(x_traj[i-1]) * dt**2
        v_traj[i] = v_traj[i-1] + 0.5 * (F(x_traj[i-1]) + F(x_traj[i])) * dt
    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 4

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
        v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt

    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Test Report

Global Parameters

Code Results

Test Run 0 Run 1 Run 2 Run 3 Run 4
aa_polarity Pass Pass Fail Pass Pass
adiabatic_expansion Pass Pass Pass Pass Pass
alignment Fail Fail Fail Fail Fail
angle Fail Pass Pass Fail Pass
aromatic_aa Pass Pass Pass Pass Pass
arrhenius Pass Fail Fail Pass Pass
bimolecular Pass Pass Pass Pass Pass
bb_rad Pass Pass Pass Pass Pass
blast Fail Fail Fail Fail Fail
braggant Pass Pass Pass Pass Pass
bravais Pass Fail Fail Fail Fail
canonicalize Pass Pass Pass Pass Pass
carnot_efficiency Pass Pass Pass Pass Pass
claussius Pass Fail Pass Pass Pass
compare_electronegativity Fail Fail Fail Fail Fail
condiff_1d Pass Pass Pass Pass Pass
cubes Fail Fail Fail Fail Fail
de_broglie Pass Pass Pass Pass Pass
derivative1d-ch Pass Pass Fail Pass Fail
derivative_2deg Pass Pass Pass Pass Pass
descriptors Fail Pass Fail Fail Fail
dipole Pass Pass Pass Pass Pass
dou Fail Fail Fail Fail Fail
eigen-ch Pass Pass Pass Pass Fail
eigen Pass Pass Pass Pass Pass
element_mass Pass Pass Pass Pass Pass
element_name Pass Pass Pass Pass Pass
energy_of_e Pass Fail Pass Fail Fail
find_indices Fail Fail Fail Pass Fail
force_constant Fail Fail Fail Fail Fail
fourier_1d Pass Pass Pass Fail Fail
freezing_depression Pass Pass Pass Pass Pass
genpos Fail Fail Fail Fail Fail
heating_water Fail Fail Fail Fail Fail
hydrophobic_res Fail Fail Fail Fail Fail
ideal_gas Pass Pass Pass Pass Pass
integral Fail Fail Fail Fail Fail
trap Pass Pass Pass Pass Pass
invert_matrix Fail Pass Fail Pass Fail
iupac2smiles Fail Fail Fail Fail Fail
karplusant Pass Fail Pass Pass Pass
kld Fail Pass Fail Pass Fail
langevin_dynamics Pass Fail Fail Fail Fail
weighted-least-squares Fail Pass Pass Fail Pass
lipinski_rule_of_five Pass Pass Pass Pass Pass
mape Fail Pass Fail Fail Fail
mapping_operator Fail Fail Fail Fail Fail
matpow Pass Fail Fail Fail Fail
matrix_factorial Fail Pass Fail Fail Fail
max-boltz Fail Pass Fail Pass Fail
michaelis Pass Pass Pass Pass Pass
mol_charge Pass Pass Pass Pass Fail
net_charge Pass Pass Pass Pass Pass
solve_ode Fail Fail Fail Fail Fail
ohe Fail Fail Fail Fail Fail
osmotic_pressure Fail Pass Pass Pass Pass
pair_wise Fail Fail Fail Fail Fail
pauli_matrices Pass Pass Pass Pass Pass
pi Pass Pass Pass Pass Pass
pib_1d Pass Pass Pass Pass Pass
pred_interval Pass Pass Pass Pass Pass
pubchem Fail Fail Fail Fail Fail
pyscf_energy Fail Fail Fail Fail Fail
qed Pass Fail Pass Pass Pass
quantile Fail Fail Pass Pass Fail
random_walk Fail Pass Pass Pass Pass
rank Pass Pass Pass Pass Pass
remove-water Pass Pass Pass Fail Pass
rms_velocity Pass Fail Fail Fail Fail
rmse Pass Pass Pass Pass Pass
rog Pass Pass Pass Pass Pass
rotationant Pass Pass Pass Pass Pass
rotation_higherant Fail Fail Fail Fail Fail
sasa Fail Fail Fail Fail Fail
scaffold Fail Fail Fail Fail Fail
seq-align Pass Pass Pass Pass Fail
seq-trans Pass Pass Pass Pass Pass
sequence Pass Fail Fail Fail Pass
sle Fail Fail Fail Fail Fail
spectral_r Fail Fail Fail Fail Pass
find_peaks Fail Fail Fail Fail Fail
speed_of_sound Fail Fail Fail Fail Fail
substructure Fail Fail Fail Fail Fail
tanimoto Pass Pass Pass Pass Pass
unbdistance Fail Fail Fail Fail Fail
velocity_verlet_integration Pass Pass Pass Pass Pass

Details

aa_polarity

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    polar_count = 0
    for aa in sequence:
        if aa in ['S', 'T', 'N', 'Q']:
            polar_count += 1
    return polar_count


sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    polar_count = 0
    for aa in sequence:
        if aa in ['S', 'T', 'N', 'Q']:
            polar_count += 1
    return polar_count


sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    polar_count = 0
    for amino_acid in sequence:
        if amino_acid in "RKEDQN":
            polar_count += 1
    return polar_count


sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    polar_count = 0
    for aa in sequence:
        if aa in ['S', 'T', 'N', 'Q']:
            polar_count += 1
    return polar_count


sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    polar = ['S', 'T', 'N', 'Q']
    count = 0
    for aa in sequence:
        if aa in polar:
            count += 1
    return count


sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

adiabatic_expansion

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1 * (P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1 * (P2/P1)**((gamma-1)/gamma)
   return T2


import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1*(P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1 * (P2/P1)**((gamma-1)/gamma)
   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

alignment

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  # align to a specific frame
  traj.superpose(traj, frame=frame_index)
  
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

'NoneType' object has no attribute 'xyz'

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  # align to the first frame
  traj.superpose(traj, frame=frame_index)
  
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

'NoneType' object has no attribute 'xyz'

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  # align to the first frame
  traj.superpose(traj, frame=frame_index)
  
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

'NoneType' object has no attribute 'xyz'

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  # align to the first frame
  traj.superpose(traj, frame=frame_index)
  
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

'NoneType' object has no attribute 'xyz'

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  # align trajectory to a specific frame
  traj.superpose(traj, frame=frame_index)
  
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

'NoneType' object has no attribute 'xyz'

angle

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    # start
    
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    cos_angle = np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
    return np.arccos(cos_angle)


import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    # start
    return np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
    
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    # start
    
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    # start
    cos_angle = np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
    return np.arccos(cos_angle)
    
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

aromatic_aa

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    aromatic = ['F', 'Y', 'W']
    aromatic_count = 0
    for aa in sequence:
        if aa in aromatic:
            aromatic_count += 1
    return aromatic_count


result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    aromatic = ['F', 'Y', 'W']
    count = 0
    for aa in sequence:
        if aa in aromatic:
            count += 1
    return count


result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    aromatic = ['F', 'Y', 'W']
    count = 0
    for aa in sequence:
        if aa in aromatic:
            count += 1
    return count


result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    aromatic = ['F', 'Y', 'W']
    aromatic_count = 0
    for aa in sequence:
        if aa in aromatic:
            aromatic_count += 1
    return aromatic_count


result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    aromatic_residues = ['F', 'Y', 'W']
    aromatic_count = 0
    for residue in sequence:
        if residue in aromatic_residues:
            aromatic_count += 1
    return aromatic_count


result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

arrhenius

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2 * math.exp((Ea/8.314)*(1/T2 - 1/T1))
   return k1

import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2 * math.exp((Ea / (8.314 * T2)) * (1 / T1 - 1 / T2))
   return k1

import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   R = 8.314
   k1 = k2*math.exp((Ea/(R*T2))*(1/T1 - 1/T2))
   return k1

import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2 * math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
   return k1

import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2 * math.exp((Ea/8.314)*((1/T2)-(1/T1)))
   return k1

import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

bimolecular

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   return k*A*B


import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   return k*A*B


import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   return k*A*B

import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   return k*A*B

import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   return k*A*B

import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

bb_rad

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34
   c = 3.0e+8
   k = 1.38e-23
   return 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))


import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34 # Planck's constant
   c = 3.0e+8 # speed of light
   k = 1.38e-23 # Boltzmann constant
   return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)

import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34
   c = 3.0e+8
   k = 1.38e-23
   a = 2.0*h*c**2
   b = h*c/(lam*k*T)
   intensity = a/ ( (lam**5) * (np.exp(b) - 1.0) )
   return intensity


import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34
   c = 3.0e+8
   k = 1.38e-23
   return 2.0*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1.0))


import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   h = 6.626e-34
   c = 3.0e+8
   k = 1.38e-23
   return (2*h*c**2/lam**5)*(1/(np.exp(h*c/(lam*k*T))-1))

import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

blast

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup
    import numpy as np

    # 2. Submit BLAST search with sequences
    url = 'http://www.uniprot.org/blast/'
    params = {'query': seq, 'format': 'fasta'}
    r = requests.get(url, params=params)

    # 3. Get result
    soup = BeautifulSoup(r.text, 'html.parser')
    result = soup.find_all('pre')[0].text

    # 4. Parse MSA
    result = result.split('\n')
    result = [i for i in result if i]
    result = [i.split(' ') for i in result]
    result = np.array(result)
    result = result[:, 1]

    # 5. Return a tuple of e score, id of top match
    return result[0], result[1]


e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

list index out of range

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    from Bio.Blast import NCBIWWW
    from Bio import SeqIO
    from Bio.Blast import NCBIXML
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio import Entrez
    from Bio import SeqIO
    from Bio import AlignIO
    from Bio.Align.Applications import ClustalwCommandline
    from Bio import Phylo
    from Bio.Phylo.TreeConstruction import DistanceCalculator
    from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
    from Bio
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

invalid syntax (<string>, line 102)

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup
    import numpy as np

    # 2. Submit BLAST search with sequences
    url = 'http://www.uniprot.org/blast/'
    params = {'query': seq, 'format': 'html'}
    r = requests.get(url, params=params)
    # 3. Get result
    soup = BeautifulSoup(r.text, 'html.parser')
    # 4. Parse MSA
    msa = soup.find_all('pre')[0].text
    # 5. Return a tuple of e score, id of top match
    return msa

e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

list index out of range

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup
    import numpy as np

    # 2. Submit BLAST search with sequences
    url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
    params = {'QUERY': seq, 'DATABASE': 'nr', 'PROGRAM': 'blastp', 'CMD': 'Put'}
    r = requests.get(url, params=params)
    # 3. Get result
    soup = BeautifulSoup(r.text, 'html.parser')
    # 4. Parse MSA
    msa = soup.find('pre', attrs={'class': 'blast_
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

EOL while scanning string literal (<string>, line 35)

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    # 1. import packages
    import requests
    from bs4 import BeautifulSoup
    import numpy as np

    # 2. Submit BLAST search with sequences
    # 2.1. Set up parameters
    # 2.1.1. Set up URL
    url = 'http://www.uniprot.org/blast/'
    # 2.1.2. Set up headers
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    # 2.1.3. Set up data
    data = {'query': seq,
            'database': 'uniprotkb',
            'format': 'fasta',
            'align': 'yes',
            'scores': 'yes',
            'alignments': '1',
            'sort': 'score',
            'order': 'descending',
            'stype': 'protein',
            'results': 'text',
            'output': 'xml'}
    # 2.2. Submit request
    r = requests.post(url, headers=headers, data=data)
    # 2.3. Get result
    result = r.text
    # 3. Parse MSA
    # 3.1. Parse result
    soup = BeautifulSoup(result, 'lxml')
    # 3.2. Get MSA
    msa = soup.find_all('pre')[1].text
    # 3.3. Get e score
    e_score = float(soup.find_all('td')[-1].text)
    # 3.4. Get top match
    top_match = soup.find_all('td')[-2].text
    # 4. Return a tuple of e score, id of top match
    return (e_score, top_match)

e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

list index out of range

braggant

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    return np.arcsin(wavelength / (2 * d))

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    return np.arcsin(wavelength / (2 * d))

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    return np.arcsin(wavelength/(2*d))

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    return np.arcsin(wavelength/(2*d))

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    return np.arcsin(wavelength / (2 * d))


import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

bravais

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number in range(1, 3):
        return "triclinic"
    elif group_number in range(3, 16):
        return "monoclinic"
    elif group_number in range(16, 75):
        return "orthorhombic"
    elif group_number in range(75, 143):
        return "tetragonal"
    elif group_number in range(143, 168):
        return "trigonal"
    elif group_number in range(168, 195):
        return "hexagonal"
    elif group_number in range(195, 231):
        return "cubic"
    else:
        return "unknown"

m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 17)

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 17)

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 17)

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    lattice = ""
    if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 18)

canonicalize

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    can_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return can_list

smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    return [Chem.MolToSmiles(Chem.MolFromSmiles(smiles), isomericSmiles=True) for smiles in smiles_list]

smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    can_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return can_list

smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return canon_list

smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    can_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
    return can_list

smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

carnot_efficiency

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   return 1 - T_cold / T_hot

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   return 1 - T_cold / T_hot

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   return 1 - T_cold / T_hot

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   efficiency = 1 - (T_cold / T_hot)
   return efficiency

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   return 1 - T_cold / T_hot

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

claussius

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   return P1 * math.exp(HVap / (8.314 * T1) * (1 / T2 - 1 / T1))

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)


import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

compare_electronegativity

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   
result = True if compare_electronegativity("O","C") else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   
result = True if compare_electronegativity("O","C") else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   
result = True if compare_electronegativity("O","C") else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
      return True
   else:
      return False

result = True if compare_electronegativity("O","C") else False

Output:

'Element' object has no attribute 'pauling_electronegativity'

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   
result = True if compare_electronegativity("O","C") else False

Output:

Success

condiff_1d

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  # start
  return x[1:] - x[:-1]
  
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  return x[1:] - x[:-1]


import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  # start
  return np.diff(x)
  
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  return x[1:] - x[:-1]


import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  return x[1:] - x[:-1]


import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

cubes

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  sum = 0
  for i in range(n):
    sum += i**3
  return sum

result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  sum = 0
  for i in range(n):
    sum += i**3
  return sum

result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  sum = 0
  for i in range(n):
    sum += i**3
  return sum

result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  sum = 0
  for i in range(n):
    sum += i ** 3
  return sum

result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  sum = 0
  for i in range(n):
    sum += i ** 3
  return sum

result = True if sum_of_cubes(5) == 225 else False

Output:

Success

de_broglie

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.62606896e-34
   c = 299792458.0
   return h / math.sqrt(m * v * v + (h * h) / (4 * c * c))

import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.6260755e-34
   c = 2.99792458e8
   return h / (m * v * c)

import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.62606876e-34
   c = 299792458.0
   return h / (m * v)

import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.62606876e-34
   c = 299792458.0
   return h / (m * v)

import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   h = 6.6260755e-34
   return h / (m * v)

import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

derivative1d-ch

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  # start
  return 2*a*x + b
  
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  return 2*a*x + b

"""
Create a matrix of zeros
"""
b = np.zeros((5,10))

import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  # 在这里完成函数
  
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  return 2*a*x + b

import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  # 在这里输入代码
  
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

derivative_2deg

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  return 2*a*x + b


import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  return 2*a*x + b

import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  # start
  return 2*a*x + b
  
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  return 2*a*x + b

import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  return 2*a*x + b

import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

descriptors

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    nms = [x[0] for x in Descriptors._descList]
    calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
    return np.array([calc.CalcDescriptors(Chem.MolFromSmiles(smile)) for smile in smiles_list])


s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    # initialize the descriptor calculator
    calc = MoleculeDescriptors.MolecularDescriptorCalculator([
        'MolWt',
        'MolLogP',
        'TPSA',
        'LabuteASA',
        'NumRotatableBonds',
        'NumHAcceptors',
        'NumHDonors',
        'NumHeteroatoms'
    ])

    # initialize the output matrix
    descriptors = np.zeros((len(smiles_list), 8))

    # loop over the SMILEs
    for i, smiles in enumerate(smiles_list):
        # convert the SMILEs to a molecule
        mol = Chem.MolFromSmiles(smiles)

        # calculate the descriptors
        descriptors[i, :] = calc.CalcDescriptors(mol)

    # return the descriptors
    return descriptors


s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    nms = [x[0] for x in Descriptors._descList]
    calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
    res = []
    for smiles in smiles_list:
        m = Chem.MolFromSmiles(smiles)
        res.append(calc.CalcDescriptors(m))
    return np.array(res)


s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    nms = [x[0] for x in Descriptors._descList]
    calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
    descriptors = []
    for smiles in smiles_list:
        m = Chem.MolFromSmiles(smiles)
        descrs = calc.CalcDescriptors(m)
        descriptors.append(descrs)
    return np.array(descriptors)


s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    nms = [x[0] for x in Descriptors._descList]
    calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
    descriptors = []
    for smile in smiles_list:
        m = Chem.MolFromSmiles(smile)
        desc = calc.CalcDescriptors(m)
        descriptors.append(desc)
    return np.array(descriptors)


s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

dipole

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole = np.zeros(3)
  for i in range(len(charges)):
    dipole += charges[i] * coordinates[i]
  return dipole

import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole = np.zeros(3)
  for i in range(len(charges)):
    dipole += charges[i] * coordinates[i]
  return dipole


import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  return np.sum(coordinates * charges[:, np.newaxis], axis=0)

import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole = np.zeros(3)
  for i in range(len(charges)):
    dipole += charges[i] * coordinates[i]
  return dipole

import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole = np.zeros(3)
  for i in range(len(charges)):
    dipole += charges[i] * coordinates[i]
  return dipole

import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

dou

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    c = mol.GetNumAtoms()
    n = 0
    h = 0
    hal = 0
    for atom in mol.GetAtoms():
        if atom.GetAtomicNum() == 7:
            n += 1
        elif atom.GetAtomicNum() == 1:
            h += 1
        elif atom.GetAtomicNum() == 9:
            hal += 1
        elif atom.GetAtomicNum() == 17:
            hal += 1
        elif atom.GetAtomicNum() == 35:
            hal += 1
        elif atom.GetAtomicNum() == 53:
            hal += 1
    rdb = (2*(c-n-h-hal)+n+hal)/2
    return rdb

d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    rdb = Descriptors.NumRadicalElectrons(mol)
    return rdb

d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.NumRadicalElectrons(mol)

d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    C = rdMolDescriptors.CalcNumAliphaticCarbocycles(mol)
    N = rdMolDescriptors.CalcNumAliphaticHeterocycles(mol)
    H = rdMolDescriptors.CalcNumAliphaticHeterocycles(mol)
    Halogen = rdMolDescriptors.CalcNumAliphaticHeterocycles(mol)
    rdbs = (2*C + 2*N + H - 2 - Halogen)/2
    return rdbs

d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    rdbs = Descriptors.NumRadicalElectrons(mol)
    return rdbs

d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

Success

eigen-ch

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    # start
    eigen_value, eigen_vector = np.linalg.eig(M)
    return eigen_value, eigen_vector
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    # begin
    eig_value, eig_vector = np.linalg.eig(M)
    return eig_value, eig_vector
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    # start
    eig_val, eig_vec = np.linalg.eig(M)
    return eig_val, eig_vec
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    eig_val, eig_vec = np.linalg.eig(M)
    return eig_val, eig_vec


import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    # 初始化特征值和特征向量
    eig_val = np.zeros(M.shape[0])
    eig_vec = np.zeros((M.shape[0], M.shape[0]))
    # 开始迭代
    for i in range(M.shape[0]):
        # 初始化特征向量
        v = np.random.rand(M.shape[0])
        # 开始迭代
        for j in range(M.shape[0]):
            # 计算特征值
            eig_val[i] = np.dot(v, np.dot(M, v)) / np.dot(v, v)
            # 计算特征向量
            v = np.dot(M, v) / np.linalg.norm(np.dot(M, v))
        # 存储特征向量
        eig_vec[:, i] = v
    return eig_val, eig_vec

"""
Compute eigenvalues and eigenvectors
"""
eig_val, eig_vec = eigen(a)

import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

shapes (5,10) and (5,) not aligned: 10 (dim 1) != 5 (dim 0)

eigen

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    eigvals, eigvecs = np.linalg.eig(M)
    return eigvals, eigvecs

import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    eigenvalues, eigenvectors = np.linalg.eig(M)
    return eigenvalues, eigenvectors

import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    # start
    eigenvalues, eigenvectors = np.linalg.eig(M)
    return eigenvalues, eigenvectors
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    # start
    eigvals, eigvecs = np.linalg.eig(M)
    return eigvals, eigvecs
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    # start
    return np.linalg.eig(M)
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

Success

element_mass

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   return mendeleev.element(element_symbol).mass

import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   element = mendeleev.element(element_symbol)
   return element.mass

import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   return mendeleev.element(element_symbol).mass

import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   return mendeleev.element(element_symbol).mass

import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   return mendeleev.element(element_symbol).mass

import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

Success

element_name

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  return mendeleev.element(element_number).symbol

result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  return mendeleev.element(element_number).symbol

result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  return mendeleev.element(element_number).symbol

result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  element = mendeleev.element(element_number)
  return element.symbol

result = True if symbol(26).lower()=="fe" else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  return mendeleev.element(element_number).symbol

result = True if symbol(26).lower()=="fe" else False

Output:

Success

energy_of_e

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    return -13.6 * (1 / (n ** 2))


import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    # start
    energy = -13.6 * (1 / n ** 2)
    

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

must be real number, not NoneType

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    # start
    e = -13.6 / n**2
    return e
    

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    # start
    energy = -13.6 * (1 / n**2)
    

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

must be real number, not NoneType

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    # start
    energy = -13.6 / (n**2)
    

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

must be real number, not NoneType

find_indices

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  ca_indices = topology.select('name CA')
  return ca_indices[0], ca_indices[1]

import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  traj = md.load(pdb_file)
  topology = traj.topology
  ca_indices = topology.select('name CA')
  return ca_indices

import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load_pdb(pdb_file)
  ca_indices = []
  for residue in pdb.topology.residues:
    if residue.is_protein:
      ca_indices.append(residue.atom(0).index)
  return ca_indices

import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

Success

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  # Load pdb file
  traj = md.load(pdb_file)
  # Get the indices of first two alpha carbon atoms
  ca_indices = [a.index for a in traj.topology.atoms if a.name == 'CA'][:2]
  return ca_indices

import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

Success

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load_pdb(pdb_file)
  ca_indices = pdb.topology.select('name CA')
  return ca_indices[0], ca_indices[1]

import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Constant' object has no attribute 'kind'

force_constant

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    # start
    k = (1.0/wave_len)*(1.0/wave_len)*(m1*m2)/(m1+m2)
    return k
    
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    # start
    return (1.0/wave_len)*(1.0/wave_len)*(m1*m2)/(m1+m2)
    
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    # begin
    mu = m1*m2/(m1+m2)
    k = (wave_len*1.0e-2)**2*mu
    return k
    
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    # begin
    return 1.0
    
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    # start
    return 1.0
    
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

fourier_1d

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  # begin
  N = len(x)
  X = np.zeros(N, dtype=np.complex)
  for k in range(N):
    for n in range(N):
      X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
  return X
  
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  N = len(x)
  X = np.zeros(N, dtype=complex)
  for k in range(N):
    for n in range(N):
      X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
  return X

import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  # start
  N = len(x)
  X = np.zeros(N, dtype=complex)
  for k in range(N):
    for n in range(N):
      X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
  return X
  
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  # start
  N = len(x)
  X = np.zeros(N, dtype=np.complex)
  for k in range(N):
    for n in range(N):
      X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
  
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  # begin
  N = len(x)
  X = np.zeros(N, dtype=np.complex)
  for k in range(N):
    for n in range(N):
      X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
  
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

freezing_depression

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   return Kf * m

import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   return Kf * m

import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   return Kf * m

import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   return Kf * m

import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   return Kf*m

import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

Success

genpos

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    table = soup.find_all('table')[1]
    rows = table.find_all('tr')
    matrices = []
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        matrices.append([ele for ele in cols if ele])
    matrices = matrices[1:]
    for i in range(len(matrices)):
        matrices[i] = matrices[i][1:]
    for i in range(len(matrices)):
        for j in range(len(matrices[i])):
            matrices[i][j] = matrices[i][j].split()
    for i in range(len(matrices)):
        for j in range(len(matrices[i])):
            for k in range(len(matrices[i][j])):
                matrices[i][j][k] = float(matrices[i][j][k])
    return matrices

import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find('table', attrs={'border': '1'})
    rows = table.find_all('tr')
    generators = []
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([ele for ele in cols if ele])
    generators = generators[1:]
    return generators

import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

'NoneType' object has no attribute 'find_all'

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    tables = soup.find_all('table')
    table = tables[1]
    rows = table.find_all('tr')
    generators = []
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([ele for ele in cols if ele])
    generators = np.array(generators)
    generators = generators[1:, 1:]
    return generators

import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-gen-matrices?gnum=" + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")
    table = soup.find_all('table')[1]
    rows = table.find_all('tr')
    matrices = []
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        matrices.append([ele for ele in cols if ele])
    return matrices

import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

"""
print requests version
"""
print(requests.__version__)
# end

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    table = soup.find_all('table')[0]
    rows = table.find_all('tr')
    generators = []
    for row in rows:
        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        generators.append([ele for ele in cols if ele])
    generators = generators[1:]
    return generators

import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

heating_water

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   return n * (T2 - T1) * 4.184

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   return n * (T2 - T1) * 4.184

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   return n * (T2 - T1) * 4.184

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   return n * 4.18 * (T2 - T1)

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   return n * (T2 - T1) * 4.184

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

hydrophobic_res

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  # Load PDB file
  pdb_file = md.load_pdb(pdb_filename)
  # Get list of residues
  residues = pdb_file.topology.residues
  # Get list of hydrophobic residues
  hydrophobic_residues = []
  for residue in residues:
    if residue.is_hydrophobic:
      hydrophobic_residues.append(residue.index)
  # Return list of hydrophobic residues
  return hydrophobic_residues

import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Residue' object has no attribute 'is_hydrophobic'

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  hydrophobic_residues = []
  with open(pdb_filename) as f:
    for line in f:
      if line.startswith('ATOM'):
        residue_name = line[17:20].strip()
        if residue_name in ['ALA', 'ILE', 'LEU', 'VAL', 'PHE', 'TRP', 'TYR']:
          residue_index = int(line[22:26].strip())
          if residue_index not in hydrophobic_residues:
            hydrophobic_residues.append(residue_index)
  return hydrophobic_residues

import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

Success

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  # load pdb file
  traj = md.load(pdb_filename)
  # get residue names
  residue_names = traj.topology.residue_names
  # get residue indices
  residue_indices = traj.topology.residue_indices
  # get hydrophobic residues
  hydrophobic_residues = []
  for i in range(len(residue_names)):
    if residue_names[i] in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TYR', 'TRP', 'MET', 'PRO']:
      hydrophobic_residues.append(residue_indices[i])
  # return hydrophobic residues
  return hydrophobic_residues

import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Topology' object has no attribute 'residue_names'

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  hydrophobic_residues = []
  with open(pdb_filename, 'r') as f:
    for line in f:
      if line.startswith('ATOM'):
        if line[17:20] in ['ALA', 'ILE', 'LEU', 'PHE', 'VAL', 'MET', 'TRP', 'TYR']:
          hydrophobic_residues.append(int(line[22:26]))
  return hydrophobic_residues

import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

Success

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  # Load PDB file
  pdb = md.load_pdb(pdb_filename)
  # Get list of hydrophobic residues
  hydrophobic_residues = []
  for residue in pdb.topology.residues:
    if residue.is_water:
      continue
    if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'MET', 'PHE', 'TRP', 'PRO']:
      hydrophobic_residues.append(residue.index)
  
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

Success

ideal_gas

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm L / mol K
   return n * R * T / V

import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm L / mol K
   return n * R * T / V

import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm L / mol K
   return n * R * T / V

import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08206 # atm L / mol K
   return n * R * T / V

import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   R = 0.08205746 # atm L / mol K
   return n * R * T / V

import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

integral

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  return a/4*d**4 + b/3*d**3 + c/2*d**2 + d


import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  return (a/4)*d**4 + (b/3)*d**3 + (c/2)*d**2 + d


import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

trap

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  s = 0.5*(f(a) + f(b))
  for i in range(1,n):
    s += f(a + i*h)
  return h*s

import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  s = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    s += f(a + i*h)
  return s*h

import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  s = 0.5*(f(a) + f(b))
  for i in range(1, n):
    s += f(a + i*h)
  return h*s


import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  s = 0.5*f(a) + 0.5*f(b)
  for i in range(1,n):
    s += f(a + i*h)
  return s*h

import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  h = (b-a)/n
  x = np.linspace(a,b,n+1)
  y = f(x)
  return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))


import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

invert_matrix

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    # start
    A_inv = np.linalg.inv(A)
    


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    # Compute the inverse of A
    A_inv = np.linalg.inv(A)
    return A_inv



import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    # Write your code here
    


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    # compute the inverse of A
    A_inv = np.linalg.inv(A)
    return A_inv



import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    # start
    A_inv = np.linalg.inv(A)
    


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

Success

iupac2smiles

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
    return Chem.MolToSmiles(mol)


iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Python argument types in
    rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
    MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    return Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC))


iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

Python argument types in
    rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
    MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)

karplusant

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    return A + B * np.cos(phi) + C * np.cos(2 * phi)


import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    return A*(1-np.exp(-B*phi))*np.cos(C*phi)


import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    return A + B*np.cos(phi) + C*np.cos(2*phi)


import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    return A + B*np.cos(phi) + C*np.cos(2*phi)


import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    return A + B*np.cos(phi) + C*np.cos(2*phi)


import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

kld

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  # YOUR CODE HERE
  # raise NotImplementedError()
  
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  # start
  return np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  # start
  kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  # start
  return np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  # start
  # Calculate the KL divergence loss
  kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
  
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

langevin_dynamics

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt)*np.random.normal()
        x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
    return x_traj,v_traj


import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        x_traj[i+1] = x_traj[i] + dt*v_traj[i]
        v_traj[i+1] = v_traj[i] - dt*gamma*v_traj[i] - dt*F(x_traj[i]) + np.sqrt(2*gamma*T*dt)*np.random.normal()
    return x_traj, v_traj


import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
        x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
    return x_traj, v_traj


import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1,n_steps):
        v_traj[i] = v_traj[i-1] + (-gamma*v_traj[i-1] + F(x_traj[i-1]) - T*gamma*np.random.randn()/m)*dt
        x_traj[i] = x_traj[i-1] + v_traj[i]*dt
    return x_traj,v_traj


import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(n_steps-1):
        x_traj[i+1] = x_traj[i] + dt*v_traj[i]
        v_traj[i+1] = v_traj[i] + dt*(-gamma*v_traj[i] - F(x_traj[i]) + np.sqrt(2*gamma*T/m)*np.random.normal())
    return x_traj,v_traj


import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

weighted-least-squares

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    # start
    
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    # Calculate the inverse of the covariance matrix
    w = np.diag(w)
    cov_inv = np.linalg.inv(np.dot(x.T, np.dot(w, x)))
    # Calculate the fit coefficients
    coeffs = np.dot(cov_inv, np.dot(x.T, np.dot(w, y)))
    return coeffs


import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    return np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)


import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    # The coefficients are given by the formula:
    # beta = (X^T W X)^-1 X^T W y
    # where W is the diagonal matrix of weights
    # and X is the matrix of predictors
    #
    # The matrix X^T W X is symmetric, so we can use the Cholesky decomposition
    # to solve the system of equations.
    #
    # First, we compute the Cholesky decomposition of X^T W X
    # L L^T = X^T W X
    #
    # Then, we solve the system of equations
    # L L^T beta = X^T W y
    # for L^T beta
    #
    # Finally, we solve the system of equations
    # L^T beta = L^-1 (X^T W y)
    # for beta
    #
    # Note that the Cholesky decomposition is more efficient than the LU
    # decomposition, and that the backsubstitution step is more efficient
    # than the forward substitution step.
    #
    # We can use the Cholesky decomposition because the matrix X^T W X is
    # symmetric and positive 
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    return np.linalg.lstsq(x.T.dot(np.diag(w)).dot(x), x.T.dot(np.diag(w)).dot(y))[0]


import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

Success

lipinski_rule_of_five

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return False
    else:
        if rdMolDescriptors.CalcNumHBD(mol) <= 5 and rdMolDescriptors.CalcNumHBA(mol) <= 10 and Descriptors.MolWt(mol) < 500 and Descriptors.MolLogP(mol) < 5:
            return True
        else:
            return False

from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    m = Chem.MolFromSmiles(smiles)
    if m is None:
        return False
    else:
        if rdMolDescriptors.CalcNumHBD(m) <= 5 and rdMolDescriptors.CalcNumHBA(m) <= 10 and Descriptors.MolWt(m) < 500 and Crippen.MolLogP(m) < 5:
            return True
        else:
            return False

from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    hbd = rdMolDescriptors.CalcNumHBD(mol)
    hba = rdMolDescriptors.CalcNumHBA(mol)
    mw = Descriptors.MolWt(mol)
    logp = Crippen.MolLogP(mol)
    if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
        return True
    else:
        return False
    
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    # create a molecule from the SMILES string
    mol = Chem.MolFromSmiles(smiles)
    # calculate the number of hydrogen bond donors
    hbd = rdMolDescriptors.CalcNumHBD(mol)
    # calculate the number of hydrogen bond acceptors
    hba = rdMolDescriptors.CalcNumHBA(mol)
    # calculate the molecular weight
    mw = Descriptors.MolWt(mol)
    # calculate the logP
    logp = Crippen.MolLogP(mol)
    # return a boolean indicating if the molecule satisfies Lipinski's rule of five
    return hbd <= 5 and hba <= 10 and mw < 500 and logp < 5

from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return False
    if rdMolDescriptors.CalcNumHBD(mol) > 5:
        return False
    if rdMolDescriptors.CalcNumHBA(mol) > 10:
        return False
    if Descriptors.MolWt(mol) > 500:
        return False
    if Crippen.MolLogP(mol) > 5:
        return False
    return True

from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

Success

mape

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  # start
  mape = np.mean(np.abs((y - y_hat) / y)) * 100
  
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  return np.mean(np.abs((y - y_hat) / y)) * 100

import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  # start
  mape = 0
  
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  # start
  mape = 0
  for i in range(len(y_hat)):
    mape += abs((y_hat[i] - y[i])/y[i])
  mape = mape/len(y_hat)
  
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  # start
  mape = 0
  for i in range(len(y)):
    mape += abs(y_hat[i] - y[i]) / y[i]
  mape /= len(y)
  
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

mapping_operator

Query

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  

Run 0

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  # Initialize the mapping matrix
  mapping_matrix = np.zeros((molecule.n_atoms, molecule.n_atoms))
  # Loop over the beads
  for bead_index, bead_selection in enumerate(beads_mappings):
    # Get the bead
    bead = molecule.select_atoms(bead_selection)
    # Loop over the atoms in the bead
    for atom in bead.atoms:
      # Get the atom index
      atom_index = atom.index
      # Set the mapping matrix
      mapping_matrix[atom_index, atom_index] = 1.0 / bead.n_atoms
  # Return the mapping matrix
  return mapping_matrix

import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'replace'

Run 1

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  # Get the number of beads
  n_beads = len(beads_mappings)
  # Get the number of atoms
  n_atoms = molecule.n_atoms
  # Create the mapping matrix
  mapping_matrix = np.zeros((n_beads, n_atoms))
  # Loop over the beads
  for bead_index, bead_mapping in enumerate(beads_mappings):
    # Get the atoms
    atoms = molecule.select_atoms(bead_mapping)
    # Get the masses
    masses = atoms.masses
    # Get the number of atoms
    n_atoms = len(atoms)
    # Get the total mass
    total_mass = masses.sum()
    # Loop over the atoms
    for atom_index, atom in enumerate(atoms):
      # Get the mass
      mass = atom.mass
      # Get the mass-mass weighted fraction
      mass_mass_weighted_fraction = mass / total_mass
      # Set the mapping matrix
      mapping_matrix[bead_index, atom.index] = mass_mass_weighted_fraction
  # Return the mapping matrix
  return mapping_matrix

import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'replace'

Run 2

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  # get the number of beads
  n_beads = len(beads_mappings)

  # get the number of atoms
  n_atoms = molecule.n_atoms

  # create the mapping matrix
  mapping_matrix = np.zeros((n_beads, n_atoms))

  # loop over the beads
  for bead_index in range(n_beads):
    # get the bead
    bead = beads_mappings[bead_index]

    # get the atoms
    atoms = bead.atoms

    # get the number of atoms
    n_atoms_bead = len(atoms)

    # loop over the atoms
    for atom_index in range(n_atoms_bead):
      # get the atom
      atom = atoms[atom_index]

      # get the atom index
      atom_index_molecule = atom.index

      # get the atom mass
      atom_mass = atom.mass

      # set the mapping matrix
      mapping_matrix[bead_index, atom_index_molecule] = atom_mass

  # return the mapping matrix
  return mapping_matrix

import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'atoms'

Run 3

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  # Get the number of beads
  nbeads = len(beads_mappings)
  # Get the number of atoms
  natoms = molecule.atoms.n_atoms
  # Initialize the mapping matrix
  mapping_matrix = np.zeros((nbeads, natoms))
  # Loop over the beads
  for i, bead in enumerate(beads_mappings):
    # Get the atoms in the bead
    atoms = molecule.select_atoms(bead)
    # Get the masses of the atoms
    masses = atoms.masses
    # Get the number of atoms in the bead
    natoms_bead = len(atoms)
    # Get the total mass of the bead
    total_mass = np.sum(masses)
    # Loop over the atoms in the bead
    for j, atom in enumerate(atoms):
      # Get the mass of the atom
      mass = masses[j]
      # Set the mapping matrix element
      mapping_matrix[i, atom.index] = mass / total_mass
  # Return the mapping matrix
  return mapping_matrix

import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'replace'

Run 4

import MDAnalysis
import numpy as np

"""
Print version string
"""
print(MDAnalysis.__version__)
# end

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  # get the number of beads
  nbeads = len(beads_mappings)
  # get the number of atoms
  natoms = molecule.atoms.n_atoms
  # create the mapping matrix
  mapping_matrix = np.zeros((nbeads, natoms))
  # loop over the beads
  for bead_index, bead_selection in enumerate(beads_mappings):
    # get the atoms for this bead
    bead_atoms = molecule.select_atoms(bead_selection)
    # loop over the atoms
    for atom in bead_atoms:
      # get the atom index
      atom_index = atom.index
      # get the atom mass
      atom_mass = atom.mass
      # set the mapping matrix element
      mapping_matrix[bead_index, atom_index] = atom_mass
  # return the mapping matrix
  return mapping_matrix

import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

'list' object has no attribute 'replace'

matpow

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  if n == 0:
    return np.identity(x.shape[0])
  elif n == 1:
    return x
  elif n % 2 == 0:
    return matpow(x.dot(x), n/2)
  else:
    return x.dot(matpow(x, n-1))

"""
Compute matrix power
"""
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = matpow(a,3)

import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  if n == 0:
    return np.eye(x.shape[0])
  elif n == 1:
    return x
  elif n % 2 == 0:
    return matpow(x.dot(x), n/2)
  else:
    return x.dot(matpow(x, n-1))

"""
Compute matrix power
"""
b = matpow(a,3)

import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  if n == 0:
    return np.eye(x.shape[0])
  elif n == 1:
    return x
  elif n % 2 == 0:
    return matpow(x.dot(x), n/2)
  else:
    return x.dot(matpow(x, n-1))

"""
Compute matrix x raised to the power n
"""
b = matpow(a, 2)

import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  if n == 0:
    return np.identity(x.shape[0])
  elif n == 1:
    return x
  elif n % 2 == 0:
    return matpow(np.dot(x,x), n/2)
  else:
    return np.dot(x, matpow(np.dot(x,x), (n-1)/2))

"""
Compute matrix x raised to the power n
"""
b = matpow(a,2)

import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  if n == 0:
    return np.identity(x.shape[0])
  elif n == 1:
    return x
  elif n % 2 == 0:
    return matpow(x.dot(x), n/2)
  else:
    return x.dot(matpow(x, n-1))

"""
Compute matrix x raised to the power n
"""
b = matpow(a,2)

import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)

matrix_factorial

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     # start
     return np.array([np.math.factorial(i) for i in n])
     

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

only integer scalar arrays can be converted to a scalar index

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     if n.shape[0] == 1 and n.shape[1] == 1:
          return np.array([[np.math.factorial(n[0,0])]])
     else:
          return np.array([[np.math.factorial(n[i,j]) for j in range(n.shape[1])] for i in range(n.shape[0])])


import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     # start
     return np.array([np.math.factorial(i) for i in n])
     

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

only integer scalar arrays can be converted to a scalar index

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     return np.prod(np.arange(1,n+1))


import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     # start
     return np.exp(np.log(np.arange(1,n+1)).sum())
     

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

max-boltz

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806488e-23 # Boltzmann constant in J/K
   return math.sqrt(k*T/M)

import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3807e-23
   return math.sqrt(3*k*T/M)


import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806503e-23 # Boltzmann's constant
   return math.sqrt(k*T/M)

import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806e-23
   return math.sqrt(3*k*T/M)

import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   k = 1.3806488e-23 # Boltzmann's constant in m^2 kg s^-2 K-1
   return math.sqrt(k*T/M)


import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

Success

michaelis

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   return Vmax * S / (Km + S)

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   return Vmax * S / (Km + S)

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   return Vmax * S / (Km + S)

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   return Vmax * S / (Km + S)

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   return Vmax * S / (Km + S)

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

mol_charge

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    return Chem.GetFormalCharge(mol)


s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    return Chem.GetFormalCharge(mol)


s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    return Chem.GetFormalCharge(mol)


s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    return Chem.GetFormalCharge(mol)


s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    return int(round(Descriptors.MolWt(mol) - Descriptors.ExactMolWt(mol)))


s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

net_charge

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for aa in sequence:
        if aa == 'K' or aa == 'R':
            charge += 1
        elif aa == 'D' or aa == 'E':
            charge -= 1
    return charge


result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for aa in sequence:
        if aa == 'K' or aa == 'R':
            charge += 1
        elif aa == 'D' or aa == 'E':
            charge -= 1
    return charge


result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    net_charge = 0
    for aa in sequence:
        if aa == 'K' or aa == 'R':
            net_charge += 1
        elif aa == 'D' or aa == 'E':
            net_charge -= 1
    return net_charge


result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    net_charge = 0
    for aa in sequence:
        if aa == 'K' or aa == 'R':
            net_charge += 1
        elif aa == 'D' or aa == 'E':
            net_charge -= 1
    return net_charge


result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    net_charge = 0
    for aa in sequence:
        if aa == 'K' or aa == 'R':
            net_charge += 1
        elif aa == 'D' or aa == 'E':
            net_charge -= 1
    return net_charge


result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

solve_ode

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    y = np.zeros((len(t), len(y0)))
    y[0] = y0
    for i in range(len(t)-1):
        h = t[i+1] - t[i]
        k1 = h * fn(t[i], y[i])
        k2 = h * fn(t[i] + h/4, y[i] + k1/4)
        k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    return y

from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    n = len(t)
    y = np.zeros((n, len(y0)))
    y[0] = y0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = fn(t[i], y[i])
        k2 = fn(t[i] + h/4, y[i] + h/4*k1)
        k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
        k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
        k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
        k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
        y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
    return y

from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    # Initialize
    y = np.zeros((len(t), len(y0)))
    y[0,:] = y0
    # Loop
    for i in range(len(t)-1):
        h = t[i+1] - t[i]
        k1 = h * fn(t[i], y[i,:])
        k2 = h * fn(t[i] + h/4, y[i,:] + k1/4)
        k3 = h * fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    return y

from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    y = np.zeros((len(t), len(y0)))
    y[0] = y0
    for i in range(1, len(t)):
        h = t[i] - t[i-1]
        k1 = h * fn(t[i-1], y[i-1])
        k2 = h * fn(t[i-1] + h/4, y[i-1] + k1/4)
        k3 = h * fn(t[i-1] + 3*h/8, y[i-1] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i-1] + 12*h/13, y[i-1] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i-1] + h, y[i-1] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i-1] + h/2, y[i-1] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i] = y[i-1] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    return y

from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    y = np.zeros((len(t), len(y0)))
    y[0,:] = y0
    for i in range(len(t)-1):
        h = t[i+1] - t[i]
        k1 = h * fn(t[i], y[i,:])
        k2 = h * fn(t[i] + h/4, y[i,:] + k1/4)
        k3 = h * fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
        k4 = h * fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
        k5 = h * fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
        k6 = h * fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
        y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
    return y

from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

ohe

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  # YOUR CODE HERE
  raise NotImplementedError()
  
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  # YOUR CODE HERE
  raise NotImplementedError()
  
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  # YOUR CODE HERE
  #raise NotImplementedError()
  
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  # YOUR CODE HERE
  #raise NotImplementedError()
  
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  # YOUR CODE HERE
  #raise NotImplementedError()
  
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

osmotic_pressure

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   return Pi*101325/(R*T)

import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   return Pi/(R*T)

import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   return Pi/(R*T)

import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   return Pi / (R * T)

import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   return Pi / (R * T)

import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

pair_wise

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  # 1
  traj = md.load(pdb_file)
  # 2
  traj.atom_slice(traj.top.select('name CA'), inplace=True)
  # 3
  pairs = np.array([pair for pair in itertools.combinations(range(traj.n_atoms), 2)])
  # 4
  return md.compute_distances(traj, pairs, periodic=False)

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  # 1
  traj = md.load(pdb_file)
  # 2
  traj.atom_slice(traj.top.select('name CA'), inplace=True)
  # 3
  pairs = np.array(list(itertools.combinations(range(traj.n_atoms), 2)))
  # 4
  distances = md.compute_distances(traj, pairs)
  return distances

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  # 1
  traj = md.load(pdb_file)
  # 2
  topology = traj.topology
  alpha_carbons = topology.select('name CA')
  # 3
  pairs = list(itertools.combinations(alpha_carbons, 2))
  # 4
  distances = md.compute_distances(traj, pairs)
  return distances

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Select only the alpha carbons
  alpha_carbons = traj.topology.select('name CA')
  # Calculate the number of unique alpha carbon pairs
  num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
  # Calculate the distances between each alpha carbon pair
  pairwise_distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
  # Return the distances between each alpha carbon pair
  return pairwise_distances

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  # 1
  traj = md.load(pdb_file)
  # 2
  alpha_carbons = traj.topology.select('name CA')
  # 3
  pairs = list(itertools.combinations(alpha_carbons, 2))
  # 4
  distances = md.compute_distances(traj, pairs)
  return distances

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

pauli_matrices

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0,1],[1,0]])
    sigma_y = np.array([[0,-1j],[1j,0]])
    sigma_z = np.array([[1,0],[0,-1]])
    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0,1],[1,0]])
    sigma_y = np.array([[0,-1j],[1j,0]])
    sigma_z = np.array([[1,0],[0,-1]])
    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    # start
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])
    return sigma_x, sigma_y, sigma_z
    

sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])
    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = np.array([[0,1],[1,0]])
    sigma_y = np.array([[0,-1j],[1j,0]])
    sigma_z = np.array([[1,0],[0,-1]])
    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

pi

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    n = 0
    for i in range(nsamples):
        x = np.random.uniform(0,1)
        y = np.random.uniform(0,1)
        if x**2 + y**2 <= 1:
            n += 1
    return 4*n/nsamples


result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(0,1,nsamples)
    y = np.random.uniform(0,1,nsamples)
    r = x**2 + y**2
    return 4*np.sum(r<1)/nsamples


result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    # create matrix of random numbers
    x = np.random.rand(nsamples,2)
    # calculate the distance from the origin
    r = np.sqrt(x[:,0]**2 + x[:,1]**2)
    # count the number of points inside the circle
    inside = np.sum(r<1)
    # calculate pi
    pi = 4*inside/nsamples
    return pi


result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    # create a matrix of random numbers
    x = np.random.rand(nsamples,2)
    # calculate the distance from the origin
    r = np.sqrt(x[:,0]**2 + x[:,1]**2)
    # count the number of points inside the unit circle
    ninside = np.sum(r<1)
    # return the value of pi
    return 4*ninside/nsamples


result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    x = np.random.uniform(-1, 1, nsamples)
    y = np.random.uniform(-1, 1, nsamples)
    z = x**2 + y**2
    return 4 * np.sum(z < 1) / nsamples


result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

pib_1d

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   E = (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
   return E

import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)


import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   return n**2*math.pi**2*hbar**2/(2*m*L**2)


import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)


import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   return n**2 * math.pi**2 * hbar**2 / (2 * m * L**2)

import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

pred_interval

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))

import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   return np.ceil(np.log(1-pred_level)/np.log(1-p))

import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   return np.ceil(np.log(1-pred_level)/np.log(1-p))

"""
Create matrix of ones
"""
a = np.ones((5,10))

import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   return np.ceil(np.log(1-pred_level)/np.log(1-p))

import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   return np.ceil(np.log(1-pred_level)/np.log(1-p))

import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

Success

pubchem

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
  response = requests.get(url)
  cids = response.text.split()
  cids = ",".join(cids)
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % cids
  response = requests.get(url)
  return set(response.text.split())


import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT?cids_type=similarity&Threshold=80' % smiles
  response = requests.get(url)
  return response.text.split()


import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT?cids_type=similarity&Threshold=80' % smiles
  response = requests.get(url)
  return set(response.text.split())


import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
  response = requests.get(url)
  cids = response.text.split()
  cids = ','.join(cids)
  url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
  response = requests.get(url)
  return set(response.text.split())


import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
  response = requests.get(url)
  cids = response.text.split()
  cids = cids[:10] # limit to 10
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
  response = requests.get(url)
  return response.text.split()


import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Success

pyscf_energy

Query

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    

Run 0

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    # Create molecule object
    mol = pyscf.gto.Mole()
    # Add atom to molecule
    mol.atom = atom
    # Set basis
    mol.basis = basis
    # Set charge and spin multiplicity
    mol.charge = 0
    mol.spin = 0
    mol.build()
    # Create HF object
    mf = pyscf.scf.RHF(mol)
    # Run SCF
    mf.kernel()
    # Return energy
    return mf.e_tot

atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 1

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.Mole()
    mol.atom = atom
    mol.basis = basis
    mol.build()
    mf = pyscf.scf.RHF(mol)
    mf.scf()
    return mf.e_tot

atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 2

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom, basis=basis, verbose=0)
    mf = pyscf.scf.RHF(mol)
    mf.kernel()
    return mf.e_tot

atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 3

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mf = pyscf.scf.RHF(mol)
    mf.scf()
    return mf.e_tot

atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 4

import pyscf
import numpy as np

"""
Print pyscf version string
"""
print(pyscf.__version__)
# end

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom, basis=basis)
    mf = pyscf.scf.RHF(mol)
    mf.kernel()
    return mf.e_tot

atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

qed

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.qed(mol)

from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.MolLogP(mol)

from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.qed(mol)

from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.qed(mol)

from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    return Descriptors.qed(mol)

from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

Success

quantile

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  # start
  return np.percentile(a, q * 100)
  
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

operands could not be broadcast together with shapes (300,) (3,) 

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  # start
  return np.percentile(a, q * 100)
  
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

operands could not be broadcast together with shapes (300,) (3,) 

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  # start
  return np.quantile(a, q)
  
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  # start
  return np.quantile(a, q)
  
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  # start
  return np.percentile(a, q * 100)
  
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

operands could not be broadcast together with shapes (300,) (3,) 

random_walk

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    x = np.zeros(N+1)
    x[0] = x0
    for i in range(N):
        x[i+1] = x[i] + a*np.random.choice([-1,1])
    return x


import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Timeout

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    x = np.zeros(N)
    x[0] = x0
    for i in range(1,N):
        x[i] = x[i-1] + a*(np.random.randint(2)*2-1)
    return x


import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    x = np.zeros(N)
    x[0] = x0
    for i in range(1,N):
        x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
    return x


import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    x = np.zeros(N)
    x[0] = x0
    for i in range(1,N):
        x[i] = x[i-1] + a*(2*np.random.randint(0,2)-1)
    return x


import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    x = np.zeros(N)
    x[0] = x0
    for i in range(1,N):
        x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
    return x


import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

Success

rank

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    u, s, v = np.linalg.svd(M)
    return np.sum(s > 1e-10)

"""
Create matrix of ones
"""
a = np.ones((5,10))

import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    # start
    U, s, V = np.linalg.svd(M)
    return np.sum(s > 1e-10)
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    return np.sum(s > 1e-10)


import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    # start
    U, s, V = np.linalg.svd(M)
    return np.sum(s > 1e-10)
    
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    return np.sum(s > 1e-10)


import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

remove-water

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  traj.remove_solvent(inplace=True)
  return traj

import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  traj.remove_solvent(inplace=True)
  return traj

import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  traj.remove_solvent(inplace=True)
  return traj

import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  traj.remove_solvent()
  return traj

import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file,top=top_file)
  traj.remove_solvent(inplace=True)
  return traj

import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

Success

rms_velocity

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23 # Boltzmann constant in SI units
   Na = 6.022140857e23 # Avogadro's number
   m = m * 1e-3 / Na # mass in kg
   return math.sqrt(3 * k * T / m)

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38e-23
   return math.sqrt(3*k*T/m)

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23 # Boltzmann constant in J/K
   return math.sqrt(3*k*T/m)

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38064852e-23 # Boltzmann constant in J/K
   return math.sqrt(3*k*T/m)

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   k = 1.38e-23
   return math.sqrt(3*k*T/m)

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

rmse

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  return np.sqrt(np.mean((a-b)**2))


import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  return np.sqrt(np.mean((a-b)**2))

import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  return np.sqrt(np.mean((a-b)**2))

import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  return np.sqrt(np.mean((a-b)**2))

import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  return np.sqrt(np.mean((a-b)**2))

import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

Success

rog

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the radius of gyration
  radius_of_gyration = md.compute_rg(traj)
  # Return the radius of gyration
  return radius_of_gyration

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  # Load the pdb
  traj = md.load(pdb_file)
  # Calculate the radius of gyration
  protein_radius_of_gyration = md.compute_rg(traj)
  # Return the radius of gyration
  return protein_radius_of_gyration

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  traj = md.load(pdb_file)
  return md.compute_rg(traj)

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the radius of gyration
  radius_of_gyration = md.compute_rg(traj)
  # Return the radius of gyration
  return radius_of_gyration

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the radius of gyration
  radius_of_gyration = md.compute_rg(traj)
  # Return the radius of gyration
  return radius_of_gyration

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

Success

rotationant

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    return B*J*(J+1)


import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    return B*J*(J+1)

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    return B*J*(J+1)


import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    return B*J*(J+1)


import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    return B*J*(J+1)


import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

rotation_higherant

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)


import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    return B*J*(J+1) - D*J*(J+1)*(J+2)*(J-1)

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

sasa

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the sasa
  sasa = md.shrake_rupley(traj)
  # Return the sasa
  return sasa

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the sasa
  sasa = md.shrake_rupley(traj)
  # Return the sasa
  return sasa

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  # Load pdb
  traj = md.load_pdb(pdb_file)
  # Calculate sasa
  sasa = md.shrake_rupley(traj)
  # Return sasa
  return sasa

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  # Load the pdb
  traj = md.load(pdb_file)
  # Calculate the sasa
  sasa = md.shrake_rupley(traj)
  # Return the sasa
  return sasa

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  # Load the pdb file
  traj = md.load(pdb_file)
  # Calculate the sasa
  sasa = md.shrake_rupley(traj)
  # Return the sasa
  return sasa

import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

Success

scaffold

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol,True))
    core = Chem.DeleteSubstructs(scaffold,Chem.MolFromSmarts('[*]'))
    return Chem.MolToSmiles(core)

smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol, True))
    core = Chem.DeleteSubstructs(scaffold, Chem.MolFromSmarts('[*]'))
    return Chem.MolToSmiles(core)

smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol, True))
    core = Chem.DeleteSubstructs(scaffold, Chem.MolFromSmarts('[*]'))
    return Chem.MolToSmiles(core)

smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    engine = MurckoScaffold.MurckoScaffoldGenerator()
    scaffold = engine.GetScaffoldForMol(mol)
    return Chem.MolToSmiles(scaffold, isomericSmiles=True)

smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

name 'MurckoScaffold' is not defined

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    engine = rdMolDescriptors.GetMorganFingerprint(mol, 2)
    arr = np.zeros((1,))
    DataStructs.ConvertToNumpyArray(engine, arr)
    return arr

smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

seq-align

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    top_aln = alns[0]
    return top_aln

seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    top_aln = alns[0]
    aln1, aln2, score, begin, end = top_aln
    return aln1, aln2

seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    top_aln = alns[0]
    aln_seq1, aln_seq2, score, begin, end = top_aln
    return aln_seq1, aln_seq2


seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    top_aln = alns[0]
    aln_seq1, aln_seq2, score, begin, end = top_aln
    return aln_seq1, aln_seq2

seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    matrix = matlist.blosum62
    gap_open = -10
    gap_extend = -0.5
    alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
    return alns

seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

Success

seq-trans

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  return Seq(gene_seq).translate()

ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  return Seq(gene_seq).translate()

ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  return Seq(gene_seq).translate()

ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  # create a sequence object
  seq_object = Seq(gene_seq)
  # translate the sequence
  protein_seq = seq_object.translate()
  # return the protein sequence
  return protein_seq

ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

"""
print biopython version
"""
print(Bio.__version__)
# end

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  return Seq(gene_seq).translate()

ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

sequence

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    # start
    return np.geomspace(s,e,l)
    
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    return np.linspace(s,e,l)

result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    return np.linspace(s,e,l)


result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    return np.linspace(s,e,l)

result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    r = (e/s)**(1/(l-1))
    return s*r**np.arange(l)

result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

sle

Query

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  

Run 0

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  eqns = [sympy.sympify(eq) for eq in eqns]
  x = sympy.symbols('x:%d' % len(eqns))
  sol = sympy.solve(eqns, x)
  return sol

from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 1

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  eqns = [sympy.parse_expr(eqn) for eqn in eqns]
  x = sympy.symbols('x:%d' % len(eqns))
  sol = sympy.solve(eqns, x)
  return sol

from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

invalid syntax (<string>, line 1)

Run 2

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  # create a list of variables
  vars = []
  for eqn in eqns:
    for var in eqn.split('+'):
      var = var.split('-')[-1]
      var = var.split('=')[0]
      var = var.strip()
      if var not in vars:
        vars.append(var)
  
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

'NoneType' object has no attribute 'values'

Run 3

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  # create a list of variables
  x = sympy.symbols('x:%d' % len(eqns))
  # create a list of equations
  eqns = [sympy.sympify(eq) for eq in eqns]
  # solve the system of equations
  sol = sympy.solve(eqns, x)
  # return the solution
  return sol

from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 4

import sympy

"""
print sympy version
"""
print(sympy.__version__)
# end

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  eqns = [sympy.sympify(eq) for eq in eqns]
  x = sympy.symbols('x:%d' % len(eqns))
  sol = sympy.solve(eqns, x)
  return sol

from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

spectral_r

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  # start
  # Calculate the eigenvalues of a
  eigvals = np.linalg.eigvals(a)
  # Calculate the spectral radius
  spectral_r = np.max(np.abs(eigvals))
  
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  # start
  eigenvalues = np.linalg.eigvals(a)
  spectral_r = np.max(np.abs(eigenvalues))
  
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  # start
  eig_vals = np.linalg.eigvals(a)
  spectral_r = np.max(np.abs(eig_vals))
  
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  # start
  eigenvalues = np.linalg.eigvals(a)
  spectral_r = np.max(np.abs(eigenvalues))
  
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  # start
  eigvals = np.linalg.eigvals(a)
  return np.max(np.abs(eigvals))
  
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

find_peaks

Query

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    

Run 0

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    # Find the peaks
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.1)
    # Sort by height
    peaks = sorted(peaks, key=lambda x: abs_spectrum[x,1], reverse=True)
    # Return the first `npeaks`
    return peaks[:npeaks]


s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 1

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    # Find the peaks
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
    # Sort the peaks by height
    peak_heights = abs_spectrum[peaks,1]
    sorted_peak_heights = np.sort(peak_heights)
    # Get the indices of the highest peaks
    indices = np.where(peak_heights >= sorted_peak_heights[-npeaks])[0]
    # Return the wavenumbers of the highest peaks
    return abs_spectrum[peaks[indices],0]


s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 2

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    # Find peaks
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
    # Sort by height
    peak_heights = abs_spectrum[peaks, 1]
    peak_wavenumbers = abs_spectrum[peaks, 0]
    sorted_indices = np.argsort(peak_heights)[::-1]
    # Return the highest `npeaks` peaks
    return peak_wavenumbers[sorted_indices[:npeaks]]


s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 3

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    # Find the peaks
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
    # Sort the peaks by height
    peaks = peaks[np.argsort(abs_spectrum[peaks,1])][::-1]
    # Return the wavenumbers of the highest peaks
    return abs_spectrum[peaks,0][:npeaks]


s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

Run 4

import numpy as np
import scipy

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    # find the peaks
    peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
    # sort the peaks by height
    peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
    # return the highest `npeaks` peaks
    return peaks[:npeaks]


s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

Success

speed_of_sound

Query

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   

Run 0

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 # J/mol/K
   return math.sqrt(gamma*R*T/m)

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 # J/mol/K
   return math.sqrt(gamma*R*T/m)

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 # J/mol/K
   return math.sqrt(gamma*R*T/m)

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 # J/mol/K
   return math.sqrt(gamma * R * T / m)


import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   R = 8.314 # J/mol/K
   return math.sqrt(gamma*R*T/m)

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

substructure

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    # create a molecule from the smiles string
    mol = Chem.MolFromSmiles(smiles)
    # create a list to store the indices of the molecules that contain the substructure
    indices = []
    # loop through the molecules in mol_list
    for i in range(len(mol_list)):
        # if the molecule contains the substructure, add the index to the list
        if mol_list[i].HasSubstructMatch(mol):
            indices.append(i)
    # return the list of indices
    return indices

import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_sub = Chem.MolFromSmiles(smiles)
    mol_sub_fp = rdMolDescriptors.GetMorganFingerprint(mol_sub, 2)
    mol_sub_fp_arr = np.zeros((1,))
    DataStructs.ConvertToNumpyArray(mol_sub_fp, mol_sub_fp_arr)
    mol_list_fp = [rdMolDescriptors.GetMorganFingerprint(x, 2) for x in mol_list]
    mol_list_fp_arr = np.zeros((len(mol_list),))
    DataStructs.ConvertToNumpyArray(mol_list_fp, mol_list_fp_arr)
    sims = DataStructs.BulkTanimotoSimilarity(mol_sub_fp, mol_list_fp)
    return [i for i, x in enumerate(sims) if x > 0.6]

import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    # create a query molecule from the smiles string
    query = Chem.MolFromSmiles(smiles)
    # create a list to store the indices of the molecules that contain the substructure
    indices = []
    # loop through the molecules in mol_list
    for i in range(len(mol_list)):
        # if the molecule contains the substructure, add the index to the list
        if mol_list[i].HasSubstructMatch(query):
            indices.append(i)
    # return the list of indices
    return indices

import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    # create a molecule from the smiles string
    mol = Chem.MolFromSmiles(smiles)
    # create a list to store the indices of the molecules that contain the substructure
    indices = []
    # loop through the mol_list
    for i in range(len(mol_list)):
        # if the molecule contains the substructure
        if mol_list[i].HasSubstructMatch(mol):
            # add the index to the list
            indices.append(i)
    # return the list of indices
    return indices

import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    # create a molecule from the smiles string
    query_mol = Chem.MolFromSmiles(smiles)
    # create a list to store the indices of the mol_list entries that contain the substructure
    indices = []
    # loop through mol_list and check each entry for the substructure
    for i, mol in enumerate(mol_list):
        # if the substructure is found, add the index to the indices list
        if mol.HasSubstructMatch(query_mol):
            indices.append(i)
    # return the indices list
    return indices

import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

tanimoto

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  # initialize empty matrix
  tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))

  # generate ECFP4 fingerprints
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]

  # calculate Tanimoto similarity
  for i in range(len(fps)):
    for j in range(i, len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
      tanimoto_matrix[j, i] = tanimoto_matrix[i, j]

  return tanimoto_matrix


import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  # generate ECFP4 fingerprints
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
  # calculate Tanimoto similarity matrix
  tanimoto_matrix = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix


import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  # generate ECFP4 fingerprints
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
  # generate Tanimoto similarity matrix
  tanimoto_matrix = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix

import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  # initialize list of fingerprints
  fps = []
  # loop over smiles list
  for smiles in smiles_list:
    # generate molecule from smiles
    mol = Chem.MolFromSmiles(smiles)
    # generate fingerprint
    fp = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits)
    # append to list
    fps.append(fp)
  # convert to numpy array
  fps_array = np.zeros((len(fps), bits), np.int32)
  for i, fp in enumerate(fps):
    DataStructs.ConvertToNumpyArray(fp, fps_array[i])
  # calculate pairwise Tanimoto similarities
  tanimoto_matrix = np.zeros((len(fps), len(fps)))
  for i in range(len(fps)):
    for j in range(len(fps)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix

import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np

"""
print rdkit version
"""
print(rdkit.__version__)
# end

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  # initialize empty matrix
  tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
  # generate ECFP4 fingerprints
  fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
  # calculate pairwise Tanimoto similarities
  for i in range(len(smiles_list)):
    for j in range(len(smiles_list)):
      tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
  return tanimoto_matrix


import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

Success

unbdistance

Query

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    

Run 0

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    # Get the index of the ligand
    lig_ind = traj.topology.select('resname ' + lig_str)
    # Get the index of the protein
    prot_ind = traj.topology.select('protein')
    # Get the center of mass of the ligand
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    # Get the center of mass of the protein
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    # Compute the distance between the two centers of mass
    dist = md.compute_distances(traj,lig_com,prot_com)
    # Return the distance
    return dist

import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    # get indices of ligand
    lig_ind = traj.topology.select('resname '+lig_str)
    # get indices of protein
    prot_ind = traj.topology.select('protein')
    # get center of mass of ligand
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    # get center of mass of protein
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    # get distance between centers of mass
    dist = md.compute_distances(traj,lig_com,prot_com)
    return dist

import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    # get the indices of the ligand
    lig_ind = traj.topology.select('resname ' + lig_str)
    # get the indices of the protein
    prot_ind = traj.topology.select('protein')
    # get the center of mass of the ligand
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    # get the center of mass of the protein
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    # get the distance between the two centers of mass
    dist = md.compute_distances(traj,lig_com,prot_com)
    return dist

import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    # get the index of the ligand
    lig_ind = traj.topology.select('resname ' + lig_str)
    # get the index of the protein
    prot_ind = traj.topology.select('protein')
    # get the center of mass of the ligand
    lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
    # get the center of mass of the protein
    prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
    # get the distance between the two centers of mass
    dist = md.compute_distances(traj,lig_com,prot_com)
    # return the distance
    return dist

import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md

"""
Print version string
"""
print(md.version.full_version)
# end

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    top = traj.topology
    prot = top.select('protein')
    lig = top.select('resname '+lig_str)
    dist = md.compute_distances(traj, [prot,lig])
    return dist

import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

velocity_verlet_integration

Query

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    

Run 0

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
        v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
    return x_traj, v_traj


import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 1

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
        v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
    return x_traj, v_traj


import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 2

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
        v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
    return x_traj, v_traj


import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 3

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])*dt**2
        v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i]) + F(x_traj[i+1]))*dt
    return x_traj, v_traj


import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Run 4

import numpy as np

"""
Create matrix of ones
"""
a = np.ones((5,10))
# end

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + v_traj[i-1]*dt + 0.5*F(x_traj[i-1])*dt**2
        v_traj[i] = v_traj[i-1] + 0.5*(F(x_traj[i-1]) + F(x_traj[i]))*dt
    return x_traj, v_traj


import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

Success

Test Report

Global Parameters

Code Results

Test Run 0 Run 1 Run 2 Run 3 Run 4
aa_polarity Fail Fail Fail Fail Fail
adiabatic_expansion Pass Fail Fail Fail Fail
alignment Fail Fail Fail Fail Fail
angle Pass Pass Pass Pass Pass
aromatic_aa Fail Fail Fail Fail Fail
arrhenius Fail Fail Fail Fail Fail
bimolecular Fail Fail Pass Fail Pass
bb_rad Fail Fail Fail Fail Fail
blast Fail Fail Fail Fail Fail
braggant Fail Fail Fail Fail Fail
bravais Fail Fail Fail Fail Fail
canonicalize Pass Pass Pass Pass Pass
carnot_efficiency Fail Fail Fail Fail Fail
claussius Fail Fail Fail Fail Fail
compare_electronegativity Fail Fail Fail Fail Fail
condiff_1d Pass Pass Pass Pass Pass
cubes Fail Fail Fail Fail Fail
de_broglie Fail Fail Pass Fail Fail
derivative1d-ch Fail Fail Fail Fail Fail
derivative_2deg Fail Fail Fail Fail Fail
descriptors Fail Fail Fail Fail Fail
dipole Fail Fail Fail Pass Fail
dou Fail Fail Fail Fail Fail
eigen-ch Fail Fail Fail Fail Fail
eigen Fail Fail Fail Fail Fail
element_mass Fail Fail Fail Fail Fail
element_name Fail Fail Fail Fail Fail
energy_of_e Fail Fail Fail Fail Fail
find_indices Fail Fail Fail Fail Fail
force_constant Fail Fail Fail Fail Fail
fourier_1d Fail Fail Fail Fail Fail
freezing_depression Fail Fail Fail Fail Fail
genpos Fail Fail Fail Fail Fail
heating_water Fail Fail Fail Fail Fail
hydrophobic_res Fail Fail Fail Fail Fail
ideal_gas Fail Fail Fail Fail Fail
integral Fail Fail Fail Fail Fail
trap Fail Fail Fail Fail Fail
invert_matrix Fail Fail Fail Fail Fail
iupac2smiles Fail Fail Fail Fail Fail
karplusant Fail Fail Fail Fail Fail
kld Fail Fail Fail Fail Fail
langevin_dynamics Fail Fail Fail Fail Fail
weighted-least-squares Fail Fail Fail Fail Fail
lipinski_rule_of_five Fail Fail Fail Fail Fail
mape Fail Fail Fail Fail Fail
mapping_operator Fail Fail Fail Fail Fail
matpow Fail Fail Fail Fail Fail
matrix_factorial Fail Fail Fail Fail Fail
max-boltz Fail Fail Fail Fail Fail
michaelis Fail Fail Fail Fail Fail
mol_charge Pass Pass Fail Pass Pass
net_charge Fail Fail Fail Fail Fail
solve_ode Fail Fail Fail Fail Fail
ohe Fail Fail Fail Fail Fail
osmotic_pressure Fail Fail Fail Fail Fail
pair_wise Fail Fail Fail Fail Fail
pauli_matrices Fail Fail Fail Fail Fail
pi Fail Fail Fail Fail Fail
pib_1d Fail Fail Fail Fail Fail
pred_interval Fail Fail Fail Fail Fail
pubchem Fail Fail Fail Fail Fail
pyscf_energy Fail Fail Fail Fail Fail
qed Fail Fail Fail Fail Fail
quantile Fail Fail Fail Fail Fail
random_walk Fail Fail Fail Fail Fail
rank Pass Pass Fail Fail Fail
remove-water Fail Fail Fail Fail Fail
rms_velocity Fail Fail Fail Fail Fail
rmse Fail Fail Fail Fail Fail
rog Fail Fail Fail Fail Fail
rotationant Fail Fail Fail Fail Fail
rotation_higherant Fail Fail Fail Fail Fail
sasa Fail Fail Fail Fail Fail
scaffold Fail Fail Fail Fail Fail
seq-align Fail Fail Fail Fail Fail
seq-trans Fail Fail Fail Fail Fail
sequence Fail Fail Fail Fail Fail
sle Fail Fail Fail Fail Fail
spectral_r Fail Fail Fail Fail Fail
find_peaks Fail Fail Fail Fail Fail
speed_of_sound Fail Fail Fail Fail Fail
substructure Fail Fail Fail Fail Fail
tanimoto Fail Fail Fail Fail Fail
unbdistance Fail Fail Fail Fail Fail
velocity_verlet_integration Fail Fail Fail Fail Fail

Details

aa_polarity

Query

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    [insert]
    return count

Run 0

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for x in sequence:
        if x == '-':
            count += 1
        else:
            count += 1


    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 1

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for char in sequence:
        if char == 'P':
            count += 1
    return count


    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 2

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for x in sequence:
        if x == 'N':
            count += 1
        elif x == 'C':
            count -= 1
    return count


    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 3

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for char in sequence:
        if char == 'A':
            count += 1
    return count


    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

Run 4

import math
import sys

def polar_count(sequence):
    """
    This function counts the number of polar uncharged amino acids in the given sequence
    """
    count = 0
    for x in sequence:
        if x == 'P':
            count += 1
        elif x == 'H':
            count += 2
        elif x == 'D':
            count += 3
        elif x == 'C':
            count += 4
        elif x == 'A':
            count += 5
        elif x == 'T':
            count += 6
        elif x == 'G':
            count += 7
        elif x == 'W':
            count += 8
        elif x == 'V':
            count += 9
        elif x == 'I':
            count += 10
        elif x == 'L':
            count += 11
        elif x == 'R':
            count += 12
        elif x == 'Y':
            count += 13
        elif x == 'K':
            count += 14
        elif x == 'M':
            count += 15
        elif x == 'F':
            count += 16
        elif x == 'J':
            count += 17
        elif x == 'S':
            count += 18
        elif x == 'T':
            count += 19
        elif x == 'W':
            count += 20
        elif x == 'Y':
            count += 21
        elif x == 'V':
            count += 22

    return count

sample_sequence = "AAAATTVVVVPPPSREREPPII"

result = True if polar_count(sample_sequence) == 3 else False

Output:

Success

adiabatic_expansion

Query

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   [insert]
   return T2

Run 0

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   

   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T1 = T1*P1
   T2 = T2*P2
   T3 = T3*P1
   T4 = T4*P2
   T5 = T5*P2
   T6 = T6*P1
   T7 = T7*P2
   T8 = T8*P2
   T9 = T9*P1
   T10 = T10*P2
   T11 = T11*P2
   T12 = T12*P1
   T13 = T13*P2
   T14 = T14*P2
   T15 = T15*P2
   T16 = T16*P1
   T17 = T17*P2
   T18 = T18*P2
   T19 = T19*P1
   T20 = T20*P2
   T21 = T21*P2
   T22 = T22*P2
   T23 = T23*P1
   T24 = T24*P2
   T25 = T25*P2
   T26 = T26*P1
   T27 = T27*P2
   T28 = T28*P2

   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

local variable 'T2' referenced before assignment

Run 2

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T1 = T1*math.exp(-gamma*P1)
   T2 = T2*math.exp(-gamma*P2)
   
if __name__ == "__main__":
   T1 = float(sys.argv[1])
   P1 = float(sys.argv[2])
   P2 = float(sys.argv[3])
   gamma = float(sys.argv[4])
   T2 = cooling(T1,P1,P2,gamma)
   print T2
   



   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Missing parentheses in call to 'print'. Did you mean print(T2)? (<string>, line 18)

Run 3

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1 + gamma*P1
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)
   T2 = T2*math.exp(-gamma*T2)

   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def cooling(T1,P1,P2,gamma):
   """
   This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
   """
   T2 = T1 + gamma*P1


   return T2

import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3

T2 = T1*((P2/P1)**((gamma-1)/gamma))

T2_codex = cooling(T1, P1, P2, gamma)

# check 
if np.isclose(T2, T2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

alignment

Query

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  [insert]
  return traj

Run 0

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj = md.load(traj)
  traj = traj.select([frame_index])



  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

expected str, bytes or os.PathLike object, not Trajectory

Run 1

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj = md.load(traj)
  traj = md.AlignTraj(traj, frame_index)



  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

expected str, bytes or os.PathLike object, not Trajectory

Run 2

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj = md.load(traj)
  traj = md.AlignTraj(traj)
  traj = md.AlignTraj(traj, frame_index)



  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

expected str, bytes or os.PathLike object, not Trajectory

Run 3

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj = md.load(traj)
  traj.select([frame_index])


|/


  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

invalid syntax (<string>, line 13)

Run 4

import mdtraj as md
import numpy as np

def align_traj(traj, frame_index):
  """
  This function aligns the given mdtraj trajectory to a specific frame
  """
  traj = md.load(traj)
  traj.select_atoms("resname *" + frame_index)



  return traj
import numpy as np
import sys
import os
import mdtraj as md

pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)


def myrmsd(trj, frame):
    xyz = trj.xyz
    xyz0 = trj.xyz[frame]
    dx = xyz-xyz0
    dx2 = (dx*dx).sum(axis=2)
    rmsd = np.sqrt(dx2.mean(axis=1))
    return rmsd


#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)

my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)

nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)

#print("nlcc rmsd", nlcc_rmsd)

result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else False

Output:

expected str, bytes or os.PathLike object, not Trajectory

angle

Query

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    [insert]
    return angle

Run 0

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))



    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))



    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))



    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))



    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def vector_angle(v1,v2):
    """
    This function returns the angle between vector v1 and vector v2.
    """
    angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))





    return angle
import numpy as np

def unit_vec(vector):
    return vector / np.linalg.norm(vector)

v1 =  [1.2,0.5,0.5]
v2 =  [-1.5,2.0,0.0]

v1_u = unit_vec(v1)
v2_u = unit_vec(v2)

angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))

angle_codex =  vector_angle(v1,v2)

if np.isclose(angle, angle_codex) == True:
    result = True
else:
    result = False

Output:

Success

aromatic_aa

Query

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    [insert]
    return count

Run 0

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for letter in sequence:
        if letter == 'A':
            count += 1
    return count


    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 1

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for x in sequence:
        if x in "ACGT":
            count += 1
    return count


    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 2

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for letter in sequence:
        if letter == 'A' or letter == 'a':
            count += 1


    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 3

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for letter in sequence:
        if letter == 'A':
            count += 1
    return count


    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

Run 4

import math
import sys

def aromatic_aa(sequence):
    """
    This function takes in an amino acid sequence and returns the number of aromatic residues there are
    """
    count = 0
    for letter in sequence:
        if letter == 'A':
            count += 1
    return count


    return count

result = True if aromatic_aa("FLRYSCV")==2 else False

Output:

Success

arrhenius

Query

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   [insert]
   return k1

Run 0

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = k2/(T2-T1)
   k2 = k1/(T2-T1)


   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 1

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = math.sqrt(T2/T1)
   k2 = math.sqrt(T2/T1)


|/


   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 16)

Run 2

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = (T2-T1)/(T2-T1)
   k2 = k1*k1/(1-k1)
   k3 = k2*k2/(1-k2)
   k4 = k3*k3/(1-k3)
   k5 = k4*k4/(1-k4)
   k6 = k5*k5/(1-k5)
   k7 = k6*k6/(1-k6)
   k8 = k7*k7/(1-k7)
   k9 = k8*k8/(1-k8)
   k10 = k9*k9/(1-k9)
   k11 = k10*k10/(1-k10)
   k12 = k11*k11/(1-k11)
   k13 = k12*k12/(1-k12)
   k14 = k13*k13/(1-k13)
   k15 = k14*k14/(1-k14)
   k16 = k15*k15/(1-k15)
   k17 = k16*k16/(1-k16)
   k18 = k17*k17/(1-k17)
   k19 = k18*k18/(1-k18)

   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

float division by zero

Run 3

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = (T2-T1)/Ea
   k2 = k1/(T2-T1)


   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

Run 4

import math
import sys

def arrhenius(k2,T2,T1,Ea):
   """
   This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
   k2 is the rate constant at temperature T2.
   Ea is the activation energy in J/mol.
   Temperatures are given in Kelvin
   """
   k1 = (T2/T1)**(k2/2)
   k2 = k1/(1+k1/Ea)


   return k1
import numpy as np

# inputs
T1 = 308.18   # in K
T2 = 333.18   # in K
R = 8.314     # J/mol.K
Ea = 108000   # J/mol
k2 = 1e-3     # M-1 s-1 

k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)

if np.isclose(k1,k1_codex) == True:
    result = True
else:
    result = False

Output:

Success

bimolecular

Query

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   [insert]
   return rate

Run 0

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B




|/

|/


   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

invalid syntax (<string>, line 14)

Run 1

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = (k*A)/(1+k*B)




|/

|/


   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

invalid syntax (<string>, line 14)

Run 2

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B





   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

Run 3

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B




|/

|/


   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

invalid syntax (<string>, line 14)

Run 4

import math
import sys

def bimolecular_rate(k,A,B):
   """
   This function returns the rate of reaction given the rate constant k and concentrations of species A and B
   """
   rate = k*A*B
   return rate


   return rate
import numpy as np

k = 2
A = 0.1
B = 0.2
rate = k*A*B

result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False

Output:

Success

bb_rad

Query

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   [insert]
   return B

Run 0

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   B = (lam**2 - T**2) / (lam*T)
   B = np.sqrt(B*B)


|/


   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 12)

Run 1

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   B = (lam**2 - T**2) / (lam*T)
   B = B * T


|/


   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 12)

Run 2

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   B = (lam**2 - T**2) / (lam**2 - T**2)
   B = np.where(B  0, B, 0)


|/


   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 9)

Run 3

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   B = (lam**2 - T**2) / (lam**2 - T**2)
   B = B**0.5



   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def bb_radiation(lam, T):
   """
   This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
   """
   B = (lam**2 - T)/(lam**2 + T**2) * (lam**2 - T) / (lam**2 - T**2)
   B = B**0.5


|/


   return B
import numpy as np
import matplotlib.pyplot as plt

# input params
h = 6.634e-34       # J.s
c = 3.0e8           # m/s
k = 1.381e-23       # J.K-1
T = 5000            # in K
lamb_val = 1.0e-6   # in m


# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)

B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)


# check
if abs((B - B_codex) / B) <= 1e-2:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 12)

blast

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    [insert]
    return e, id

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    seq = str(seq)
    seq = str(seq).upper()
    seq = str(seq).lower()
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')
    seq = str(seq).replace('.', '')
    seq = str(seq).replace('/', '')
    seq = str(seq).replace('+', '')
    seq = str(seq).replace('-', '')

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

name 'e' is not defined

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    seq = str(seq)
    seq = str(seq.upper())
    seq = str(seq.lower())
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

name 'e' is not defined

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    seq = str(seq)
    seq = str(seq).upper()
    seq = str(seq).lower()
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")
    seq = str(seq).replace("/","")
    seq = str(seq).replace("-","")
    seq = str(seq).replace(".","")

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

name 'e' is not defined

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

name 'e' is not defined

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

def blast(seq):
    '''
    Returns MSA with a BLAST search. Uses beautiful soup
    to parse result.

    1. import packages
    2. Submit BLAST search with sequences
    3. Get result
    4. Parse MSA
    5. Return a tuple of e score, id of top match
    '''
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)
    seq = str(seq)

    return e, id
e, id = blast('>seq1\n'
              'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30

Output:

name 'e' is not defined

braggant

Query

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    [insert]
    return theta

Run 0

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arctan(wavelength/d)


|/ file dstars=1 
|/|/|/|/|/|/

    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arctan(wavelength/d)


|/ file dstars=0 
|/|/|/|/|/|/|/

    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

Run 2

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arctan(wavelength / d)





    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arctan(wavelength/d)


|/ file dstars=1 

    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

Run 4

import numpy as np

def bragg_angle(wavelength, d):
    """
    Returns the angle for Bragg scattering at wavelength and spacing d
    """
    theta = np.arctan(wavelength / d)


|/ file dstars=1 
|/|/|/|/|/

    return theta

import numpy as np

wavelength = 0.05 #nm
d = 0.3 #nm
theta = np.arcsin(wavelength/(2*d))

theta_codex = bragg_angle(wavelength, d)
print(theta, theta_codex)

if np.isclose(theta, theta_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

bravais

Query

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    [insert]
    return name

Run 0

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    group_number = int(group_number)
    lattice = {

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 13)

Run 1

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    group_number = int(group_number)
    lattice = {
        0: 'X',
        1: 'Y',
        2: 'Z',
        3: 'A',
        4: 'B',
        5: 'C',
        6: 'D',
        7: 'E',
        8: 'F',
        9: 'G',
        10: 'H',
        11: 'I',
        12: 'J',
        13: 'K',
        14: 'L',
        15: 'M',
        16: 'N',
        17: 'O',
        18: 'P',
        19: 'Q',
        20: 'R',
        21: 'S',
        22: 'T',
        23: 'U',
        24: 'V',
        25: 'W',
        26: 'X',
        27: 'Y',
        28: 'Z',
        29: 'A',
        30: 'B',
        31: 'C',
        32: 'D',
        33: 'E',
        34: 'F',
        35: 'G',
        36: 'H',
        37: 'I',
        38: 'J',
        39: 'K',
        40: 'L',

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 54)

Run 2

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    group_number = int(group_number)
    group_number = group_number - 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

name 'name' is not defined

Run 3

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    group_number = int(group_number)
    if group_number  1:
        raise ValueError("Group number must be greater than 0")
    group_number = math.floor(group_number)
    group_number = group_number - 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 2
    group_number = group_number + 1

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

invalid syntax (<string>, line 11)

Run 4

import math
import sys


def bravais_lattice(group_number):
    """
    Return bravais lattice name given space group number
    """
    group_number = int(group_number)
    group_number = group_number - 1
    group_number = group_number % 2
    group_number = group_number + 1
    group_number = group_number % 4
    group_number = group_number + 1
    group_number = group_number % 8
    group_number = group_number + 1
    group_number = group_number % 16
    group_number = group_number + 1
    group_number = group_number % 32
    group_number = group_number + 1
    group_number = group_number % 64
    group_number = group_number + 1
    group_number = group_number % 128
    group_number = group_number + 1
    group_number = group_number % 256
    group_number = group_number + 1
    group_number = group_number % 512
    group_number = group_number + 1
    group_number = group_number % 1024
    group_number = group_number + 1
    group_number = group_number % 2048
    group_number = group_number + 1
    group_number = group_number % 4096
    group_number = group_number + 1
    group_number = group_number % 8192
    group_number = group_number + 1
    group_number = group_number % 16384
    group_number = group_number + 1
    group_number = group_number % 32768
    group_number = group_number + 1

    return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'

Output:

name 'name' is not defined

canonicalize

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    [insert]
    return canon_list

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canonical_list = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        if mol is not None:
            canonical_list.append(Chem.MolToSmiles(mol))
    return canonical_list


    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canonical_mol = Chem.MolToSmiles(mol, canonical=True)
        canon_list.append(canonical_mol)


    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smiles in smiles_list:
        mol = Chem.MolFromSmiles(smiles)
        canonical_mol = Chem.MolToSmiles(mol, canonical=True)
        canon_list.append(canonical_mol)


    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
        canon_list.append(canonical_smiles)


    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def canonical(smiles_list):
    """
    Returns list of canonical forms of given molecules
    """
    canon_list = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        canonical_smiles = Chem.MolToSmiles(mol)
        canon_list.append(canonical_smiles)


    return canon_list
smiles = [
    'C1=CC=CN=C1',
    'c1cccnc1',
    'C([H])C'
]

ref_csmiles = [
    'c1ccncc1',
    'c1ccncc1',
    'CC'
]

csmiles = canonical(smiles)

print(csmiles)
print(ref_csmiles)

result = True
for r, c in zip(ref_csmiles, csmiles):
    result = result and r == c

Output:

Success

carnot_efficiency

Query

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   [insert]
   return eps

Run 0

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = T_hot / T_cold
   eps = math.ceil(eps)



   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = T_hot / T_cold
   eps = math.pow(eps, 1.5)



   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = math.pow(T_hot / T_cold, 2)



   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = T_hot / T_cold
   if eps  0.1:
      eps = 0.1
 1.0:
      eps = 1.0
   return eps




   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 10)

Run 4

import math
import sys

def carnot_efficiency(T_hot, T_cold):
   """
   This function returns the efficiency of a carnot efficiency operating between two temperatures
   """
   eps = T_hot / T_cold
   if eps  0.1:
      eps = 0.1
 1:
      eps = 1
   return eps


   return eps

import numpy as np

T_cold = 300
T_hot = 600

eps = 1 - T_cold/T_hot

eps_codex = carnot_efficiency(T_hot, T_cold)

# check 
if np.isclose(eps, eps_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 10)

claussius

Query

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   [insert]
   return P2

Run 0

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = T2 * math.exp(-1*HVap*T1)
   P2 = P1 + P2 - P1



   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1 * math.exp(-(HVap - T2) / (T2 - T1))



   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)



   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)



   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def claussius(HVap, T1, P1, T2):
   """
   This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
   """
   T1 = float(T1)
   P1 = float(P1)
   T2 = float(T2)
   P2 = T2 * math.exp(-(HVap - T1)/T2)



   return P2

import numpy as np

# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300     # in K 
T2 = 350 

P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))

# check 
if np.isclose(P2, P2_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

compare_electronegativity

Query

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   [insert]
   return result

Run 0

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   electronegativity = mendeleev.electronegativity(element1,element2)
 0.2:
      return True
   else:
      return False


   return result
result = True if compare_electronegativity("O","C") else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 1

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   electronegativity = mendeleev.electronegativity(element1,element2)
 mendeleev.electronegativity(element2,element1)



   return result
result = True if compare_electronegativity("O","C") else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 2

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   electronegativity = mendeleev.electronegativity(element1,element2)
 mendeleev.electronegativity(element2,element1)



   return result
result = True if compare_electronegativity("O","C") else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 3

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   electronegativity = mendeleev.electronegativity(element1,element2)
 mendeleev.electronegativity(element2,element1)



   return result
result = True if compare_electronegativity("O","C") else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 4

import math
import sys

def compare_electronegativity(element1,element2):
   """
   This function returns True if element1 has a larger Pauling electronegativity than element2
   """
   import mendeleev
   electronegativity = mendeleev.electronegativity(element1,element2)
 0.0



   return result
result = True if compare_electronegativity("O","C") else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

condiff_1d

Query

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  [insert]
  return diff

Run 0

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.diff(x)



  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 1

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.diff(x)



  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 2

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.diff(x)



  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 3

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.diff(x)



  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 4

import numpy as np

def condiff_1d(x):
  """
  This function computes the difference between consecutive elements in array x.
  """
  diff = np.diff(x)



  return diff
import numpy as np

x = np.array([1, 2, 4, 7, 0])

true_y = np.ediff1d(x)

pred_y = condiff_1d(x)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

cubes

Query

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  [insert]
  return s

Run 0

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = n
  for i in range(1, int(math.sqrt(n))+1):
    s *= i
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 1

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = n
  for i in range(2, int(math.sqrt(n))+1):
    s *= i
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 2

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = n
  for i in range(1, n+1):
    s *= i
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 3

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = n
  for i in range(2, int(math.sqrt(n))+1):
    s *= i
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

Run 4

import math
import sys

def sum_of_cubes(n):
  """
  This function returns the sum of the first n cubes
  """
  s = n
  for i in range(1, n+1):
    s *= i


  return s
result = True if sum_of_cubes(5) == 225 else False

Output:

Success

de_broglie

Query

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   [insert]
   return l

Run 0

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l=math.sqrt(m*m+v*v)




|/

|/













   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

invalid syntax (<string>, line 14)

Run 1

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = m*v
   l = math.sqrt(l)
   
if __name__ == "__main__":
   m = float(sys.argv[1])
   v = float(sys.argv[2])
   print de_broglie(m,v)




   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

invalid syntax (<string>, line 15)

Run 2

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l = (m*v)/(2*math.pi)


























   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

Run 3

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   l=math.sqrt(m*m+v*v)




|/





























|/



   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

invalid syntax (<string>, line 14)

Run 4

import math
import sys

def de_broglie(m,v):
   """
   This function returns the de Broglie wavelength for a particle of mass m with speed v.
   """
   
   l=math.sqrt(m*m+v*v)


   return l
import numpy as np

# input params
h = 6.626e-34 
v = 1.00e6
m = 9.11e-31

lam  = h/(m*v)
print("lam =", lam)

lam_codex = de_broglie(m,v)

# check 
if np.isclose(lam, lam_codex) ==  True:
    result = True
else:
    result = False




Output:

Success

derivative1d-ch

Query

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  [insert]
  return d

Run 0

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  dx=(b-a)/c
  dy=(b+a)/c



  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'd' is not defined

Run 1

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  dx=(b-a)/(c*x)
  dy=(a-b)/(c*x)


  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'd' is not defined

Run 2

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  dx=(a*x-b)**2+c
  dy=(a*x-b)
  dz=(b*x-c)



  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'd' is not defined

Run 3

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  dx=(b-a)/(c*x)
  return dx


  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 4

import numpy as np

def find_derivative(a,b,c,x):
  """
  这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。

  """
  dx=(b-a)/c
  dy=(b+a)/c
  dz=(b-a)/c



  return d
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'd' is not defined

derivative_2deg

Query

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  [insert]
  return deriv

Run 0

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = np.poly1d([a,b,c])
  deriv.x = x



  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

Success

Run 1

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = np.poly1d(np.polyfit(x,y,2))



  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'y' is not defined

Run 2

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = np.poly1d(np.polyfit(x,y,2))



  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'y' is not defined

Run 3

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = np.poly1d(np.polyfit(x,y,2))




  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'y' is not defined

Run 4

import numpy as np

def find_derivative(a,b,c,x):
  """
  This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
  """
  deriv = np.poly1d(np.polyfit(x,y,2))



  return deriv
import numpy as np

result = True if find_derivative(1,2,3,2) == 6 else False 

Output:

name 'y' is not defined

descriptors

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    [insert]
    return descriptors

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))


    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=8, useFeatures=False))


    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=8, nBits=2048))


    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=8, nBits=2048))


    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import numpy as np

def get_descriptors(smiles_list):
    """
    Returns an N x 8 matrix of descriptors for given SMILEs
    """
    descriptors = []
    for smi in smiles_list:
        mol = Chem.MolFromSmiles(smi)
        descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))


    return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else False

Output:

module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'

dipole

Query

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  [insert]
  return dipole_moment

Run 0

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  i', charges, coordinates)



  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

EOL while scanning string literal (<string>, line 11)

Run 1

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole = np.zeros((len(coordinates), len(charges)))
  for i in range(len(charges)):
    dipole[i, charges[i]] = np.power(coordinates[i, 0] - coordinates[i, 1], 2)
  return dipole


  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Run 2

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  i', charges, coordinates)



  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

EOL while scanning string literal (<string>, line 11)

Run 3

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.zeros(3)
  for i in range(3):
    dipole_moment[i] = np.sum(charges * coordinates[:,i])



  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

Run 4

import numpy as np

def dipole_moment(coordinates, charges):
  """
  This function returns the dipole moment of a molecule

  Coordinates is a numpy array of size Nx3
  Charges is a numpy array of size N
  """
  dipole_moment = np.zeros(3)
  for i in range(3):
    dipole_moment[i] = charges[i] * np.sum(coordinates[:,i])



  return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges) 

#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else False

Output:

Success

dou

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    [insert]
    return d

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(0))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(1))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(2))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(3))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(4))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(5))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(6))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(7))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(8))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(9))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(10))

    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

module 'rdkit.Chem' has no attribute 'RemoveAtoms'

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)

    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

name 'd' is not defined

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    bonds = mol.GetBonds()
    bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATICDOUBLE]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATICTRIPLE]

    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

name 'd' is not defined

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    bonds = mol.GetBonds()
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]

    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

name 'd' is not defined

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def calc_rdbs(smiles):
    """
    Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
    """
    mol = Chem.MolFromSmiles(smiles)
    bonds = mol.GetBonds()
    bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
    bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
    bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]

    return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4

Output:

name 'd' is not defined

eigen-ch

Query

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    [insert]
    return w,v

Run 0

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w, v = np.linalg.eig(M)




|/



|/


    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 13)

Run 1

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w, v = np.linalg.eig(M)




|/



|/





|/


    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 13)

Run 2

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w, v = np.linalg.eig(M)




|/

|/



    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 13)

Run 3

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w, v = np.linalg.eig(M)


|/v



|/





    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 11)

Run 4

import numpy as np

def eigen(M):
    """
    该函数返回矩阵M的特征值和特征向量。
    """
    w, v = np.linalg.eig(M)


|/ file dstars=0 

|/









    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 11)

eigen

Query

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    [insert]
    return w,v

Run 0

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w, v = np.linalg.eig(M)




|/













|/



    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 13)

Run 1

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w, v = np.linalg.eig(M)










|/











|/

|/


    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 19)

Run 2

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w, v = np.linalg.eig(M)


|/v



|/v







    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 11)

Run 3

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w, v = np.linalg.eig(M)




|/

|/

|/





|/



    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 13)

Run 4

import numpy as np

def eigen(M):
    """
    Return eigenvalues and eigenvectors for a square matrix M
    """
    w, v = np.linalg.eig(M)






|/





|/

|/



    return w,v
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else False

Output:

invalid syntax (<string>, line 15)

element_mass

Query

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   [insert]
   return mass

Run 0

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.elements.masses[element_symbol]



   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

module 'mendeleev.elements' has no attribute 'masses'

Run 1

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.elements.mass(element_symbol)



   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

module 'mendeleev.elements' has no attribute 'mass'

Run 2

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.elements.masses[element_symbol]



   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

module 'mendeleev.elements' has no attribute 'masses'

Run 3

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.elements.masses[element_symbol]



   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

module 'mendeleev.elements' has no attribute 'masses'

Run 4

import math
import sys

def element_mass(element_symbol):
   """
   This function returns the mass of the chemical element given by its symbol
   """
   import mendeleev
   mass = mendeleev.mass(element_symbol)



   return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else False

Output:

module 'mendeleev' has no attribute 'mass'

element_name

Query

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  [insert]
  return s

Run 0

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.symbol(element_number)


|/


  return s
result = True if symbol(26).lower()=="fe" else False

Output:

invalid syntax (<string>, line 13)

Run 1

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.symbol(element_number)


|/


  return s
result = True if symbol(26).lower()=="fe" else False

Output:

invalid syntax (<string>, line 13)

Run 2

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.symbol(element_number)


|/


  return s
result = True if symbol(26).lower()=="fe" else False

Output:

invalid syntax (<string>, line 13)

Run 3

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.symbol(element_number)


|/


  return s
result = True if symbol(26).lower()=="fe" else False

Output:

invalid syntax (<string>, line 13)

Run 4

import math
import sys

def symbol(element_number):
  """
  This function returns the two letter symbol for the chemical element given by element_number
  """
  import mendeleev
  s = mendeleev.symbol(element_number)


  return s
result = True if symbol(26).lower()=="fe" else False

Output:

module 'mendeleev' has no attribute 'symbol'

energy_of_e

Query

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    [insert]
    return energy

Run 0

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = 0.0
    for i in range(1, int(math.log(n, 2))+1):
        energy += (i*i)



    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 1

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = n * (n * (n + 1)) / 2
    return energy


    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 2

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = 0.
    for i in range(1,n+1):
        energy += i


    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 3

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = n * (n * (n + 1) / 2)
    return energy


    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

Run 4

import math
import sys

def energy_of_e(n):
    """
    This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
    """
    energy = 0.
    for i in range(1,n+1):
        energy += (i**3)


    return energy

import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)

result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)

Output:

Success

find_indices

Query

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  [insert]
  return idx

Run 0

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load(pdb_file)
  atoms = pdb.select('CA')
  idx = np.where(atoms.select('CA') == True)[0]



  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

'Trajectory' object has no attribute 'select'

Run 1

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load(pdb_file)
  atoms = pdb.select('CA')
 0)[0]



  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 2

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load(pdb_file)
  atoms = pdb.select('CA')
 0)[0]



  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

Run 3

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load(pdb_file)
  atoms = pdb.select('CA')
  idx = np.where(atoms.select('CA').xyz[0]  0)[0]




|/


  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

invalid syntax (<string>, line 11)

Run 4

import mdtraj as md
import numpy as np

def get_ca_indices(pdb_file):
  """
  This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
  """
  pdb = md.load(pdb_file)
  atoms = pdb.select('CA')
 0)[0]



  return idx
import os
import numpy as np

pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")

def get_pair_indices(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    top = pdb.topology
    CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
    indices_pair = np.array([CAs[0], CAs[1]])
    return indices_pair

my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)

result = True if np.all(my_indices_pair == prompt_indices_pair) else False

Output:

unindent does not match any outer indentation level (<string>, line 11)

force_constant

Query

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    [insert]
    return k

Run 0

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = m1/m2 - m1/m2*wave_len**2 - (m1/m2)**2 - (m1/m2)*wave_len*wave_len
    return k


    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = m1/m2
    k = k*wave_len


|/|/


    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 14)

Run 2

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = m1/m2 # reduced mass
    k = k*wave_len**2 # wave length in cm^-1 units


|/



    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 14)

Run 3

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = m1/m2 # reduced mass


|/




    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 13)

Run 4

import numpy as np

def compute_k(m1,m2,wave_len):
    """
    Two atom harmonic oscillator.
    Returns force constant in kg/s**2 units given masses m1,m2 and wave length
    wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
    """
    k = m1/m2 # reduced mass
    k = k*wave_len**2 # wave length in cm^-1 units


|/


    return k
import numpy as np

m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi

mu = (m1*m2)/(m1+m2)*mass_fac 
omega = 2*pi*wave_len*velocity 
force_const = mu*omega**2

force_const_codex = compute_k(m1,m2,wave_len)

if np.isclose(force_const, force_const_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 14)

fourier_1d

Query

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  [insert]
  return w

Run 0

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)


|/







  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)


|/

|/ file dstars=0 







  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

invalid syntax (<string>, line 11)

Run 2

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)


|/









  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

invalid syntax (<string>, line 11)

Run 3

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)


|/






  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

invalid syntax (<string>, line 11)

Run 4

import numpy as np

def fourier_1d(x):
  """
  This function returns the one dimensional fourier transform of array x.
  """
  w = np.fft.fft(x)


|/

|/ file dstars=0 







|/



  return w
import numpy as np
from numpy.fft import fft

x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])

true_y = fft(x)

test_y = fourier_1d(x)

result = True if np.allclose(true_y, test_y) else False

Output:

invalid syntax (<string>, line 11)

freezing_depression

Query

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   [insert]
   return deltaT

Run 0

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   Kf=Kf/1000.0
   deltaT=Kf*m
   if deltaT0:
      deltaT=0
   else:
      deltaT=deltaT*1000.0
   return deltaT


   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

name 'deltaT0' is not defined

Run 1

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT=Kf*m
   if deltaT0:
      deltaT=0
   return deltaT


   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

name 'deltaT0' is not defined

Run 2

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT=Kf*m
   if deltaT0:
      deltaT=0
   return deltaT


   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

name 'deltaT0' is not defined

Run 3

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   Kf = Kf/1000
   m = m/1000
   deltaT = Kf*m
   deltaT = deltaT/1000
   
if __name__ == "__main__":
   Kf = float(sys.argv[1])
   m = float(sys.argv[2])
   print freezing_depression(Kf,m)

|/


   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

invalid syntax (<string>, line 19)

Run 4

import math
import sys

def freezing_depression(Kf,m):
   """
   This function returns the decrease in freezing point in Kelvin
   The depression constant is Kf in K kg/mol and is greater than zero
   Molality m is given in mol/kg
   """
   deltaT = Kf*m/(Kf+m)
   if deltaT  0:
      deltaT = 0
   else:
      deltaT = math.ceil(deltaT)
   return deltaT




   return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else False

Output:

invalid syntax (<string>, line 12)

genpos

Query

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    [insert]
    return generators

Run 0

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    generators = []
    generators.append(gnum)
    generators.append(gnum+1)
    generators.append(gnum+2)
    generators.append(gnum+3)
    generators.append(gnum+4)
    generators.append(gnum+5)
    generators.append(gnum+6)
    generators.append(gnum+7)
    generators.append(gnum+8)
    generators.append(gnum+9)
    generators.append(gnum+10)
    generators.append(gnum+11)
    generators.append(gnum+12)
    generators.append(gnum+13)
    generators.append(gnum+14)
    generators.append(gnum+15)
    generators.append(gnum+16)
    generators.append(gnum+17)
    generators.append(gnum+18)
    generators.append(gnum+19)
    generators.append(gnum+20)
    generators.append(gnum+21)
    generators.append(gnum+22)
    generators.append(gnum+23)
    generators.append(gnum+24)
    generators.append(gnum+25)
    generators.append(gnum+26)
    generators.append(gnum+27)
    generators.append(gnum+28)
    generators.append(gnum+29)

    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

Success

Run 1

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    generators = []
    for g in range(1, gnum+1):

    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

expected an indented block (<string>, line 13)

Run 2

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    generators = []
    for i in range(1, gnum+1):
        generators.append(i)


|/


    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

invalid syntax (<string>, line 15)

Run 3

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    generators = []
    for i in range(1, gnum+1):
        generators.append(i)


|/


    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

invalid syntax (<string>, line 15)

Run 4

import requests
from bs4 import BeautifulSoup
import numpy as np

def matrix_generators(gnum):
    """ Returns list of matrix generators for general positions of given space group
    gnum -  International Tables for Crystallography space group number
    """
    generators = []
    

    return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
                [0, 1, 0, 1/2],
                [0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)

Output:

list index out of range

heating_water

Query

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   [insert]
   return q

Run 0

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = 0.0
   for x in range(0, n):
      q += (T1 * math.log(x/T2))
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

math domain error

Run 1

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = 0
   for j in range(n):
      q += (T1 * math.pow(T2, j))
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * (T1 * T2)
   q = q / 1000
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = 0
   for j in range(n):
      q += (T1 - T2) * (T1 - T2) / ((T1 - T2) * (T1 - T2))
      T1 = T2
      T2 = T1 + T1
   
   
if __name__ == "__main__":
   n = int(sys.argv[1])
   T1 = float(sys.argv[2])
   T2 = float(sys.argv[3])
   
   print heating_energy(n, T1, T2)
   



   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 21)

Run 4

import math
import sys

def heating_energy(n, T1, T2):
   """
   This function returns the energy in kcal required to heat n moles of water from T1 to T2
   """
   q = n * (T1 * T2)


   return q

import numpy as np

n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories

q_codex = heating_energy(n, T1, T2)

# check 
if np.isclose(q, q_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

hydrophobic_res

Query

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  [insert]
  return resids

Run 0

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  pdb = md.load(pdb_filename)
  resids = []
  for model in pdb.models:
    for atom in model.atoms:
      resids.append(atom.residue.index)



  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

'Trajectory' object has no attribute 'models'

Run 1

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  pdb = mdtraj.load(pdb_filename)
  resids = []
  for model in pdb.models:
    for residue in model.residues:
      if residue.resname!= 'H':
        resids.append(residue.index)



  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

name 'mdtraj' is not defined

Run 2

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  pdb = mdtraj.load(pdb_filename)
  resids = []
  for chain in pdb.chains:
    for residue in chain.residues:
      if residue.resname!= 'H':
        resids.append(residue.index)



  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

name 'mdtraj' is not defined

Run 3

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  pdb = mdtraj.load(pdb_filename)
  resids = []
  for model in pdb.models:
    for residue in model.residues:
      if residue.resname!= 'H' and residue.resname!= 'HB':
        resids.append(residue.index)



  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

name 'mdtraj' is not defined

Run 4

import mdtraj as md
import numpy as np

def get_hydrophobic_residues(pdb_filename):
  """
  Returns list of hydrophobic residues indices
  """
  pdb = mdtraj.load(pdb_filename)
  resids = []
  for model in pdb.models:
    for residue in model.residues:
      if residue.resname!= "H":
        resids.append(residue.index)



  return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
    :3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
    _FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else False

Output:

name 'mdtraj' is not defined

ideal_gas

Query

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   [insert]
   return P

Run 0

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   P = V*T*math.exp(-(n/V)**2) # pressure in atm


   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   P = V*math.exp(-T/n)



   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   P = V*T/(n*math.pow(10,9))



   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   P = V*T*math.exp(-n/(2*T))


   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def ideal_gas_pressure(n,V,T):
   """
   This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
   The pressure returned is in atm units.
   """
   P = V*T*math.exp(-n/2)
   P *= (1-math.exp(-n/2))


|/ file dstars=0 


   return P
import numpy as np

# input
V = 20.0    # volume (in L)
n = 10.0    # in moles
R = 0.08206  # in L.atm/mol.K
T = 350     # in K 

P = n*R*T/V
#print("Pressure =", P)

codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check 
if np.isclose(P, codex_pressure, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 14)

integral

Query

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  [insert]
  return integral

Run 0

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = np.poly1d([a,b,c,d])


|/ file dstars=1 



  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

invalid syntax (<string>, line 12)

Run 1

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = np.poly1d([a,b,c,d])





  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 2

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = np.poly1d([a,b,c,d])




  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 3

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = np.poly1d([a,b,c,d])





  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

Success

Run 4

import numpy as np

def find_integral(a,b,c,d):
  """
  This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.

  """
  integral = np.poly1d([a,b,c,d])


|/ file dstars=0 


  return integral
import numpy as np

result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False 

Output:

invalid syntax (<string>, line 12)

trap

Query

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  [insert]
  return integral

Run 0

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  integral = 0
  for i in range(n):
    integral += f(a) * np.exp(-(b - a) * i)



  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 1

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  integral = 0
  for i in range(n):
    integral += f(a) * f(b) / i



  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 2

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  integral = 0
  for i in range(n):
    integral += f(a) * np.exp(-(b - a) * i)



  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 3

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  integral = 0
  for i in range(n):
    integral += f(a) * np.exp(-(b - a) * i)



  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

Run 4

import numpy as np

def trap(f, n, a, b):
  """
  This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
  """
  integral = 0
  for i in range(n):
    integral += f(a) * np.exp(-b * i)



  return integral
import numpy

def f(x):
    return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))

a = 0
b = 5
n = 100

x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)

result = True if np.isclose(trap(f,n,a,b),test_intgr) else False

Output:

Success

invert_matrix

Query

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    [insert]
    return Ainv

Run 0

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

name 'Ainv' is not defined

Run 1

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

name 'Ainv' is not defined

Run 2

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

name 'Ainv' is not defined

Run 3

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    
    Ainv = np.linalg.inv(A)


|/


    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

invalid syntax (<string>, line 12)

Run 4

import numpy as np

def invert_matrix(A):
    """
    This function computes the inverse of matrix A
    """
    
    Ainv = np.linalg.inv(A)


|/





    return Ainv


import numpy as np

x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])

result = np.array_equal(m_i,x_i)



Output:

invalid syntax (<string>, line 12)

iupac2smiles

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    [insert]
    return SMILES

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    IUPAC = IUPAC.upper()
    IUPAC = IUPAC.replace('-', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')

    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

name 'SMILES' is not defined

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    IUPAC = IUPAC.upper()
    IUPAC = IUPAC.replace('-', '')
    IUPAC = IUPAC.replace(' ', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('[', '')
    IUPAC = IUPAC.replace(']', '')
    IUPAC = IUPAC.replace('{', '')
    IUPAC = IUPAC.replace('}', '')
    IUPAC = IUPAC.replace(',', '')
    IUPAC = IUPAC.replace('.', '')
    IUPAC = IUPAC.replace('-', '')
    IUPAC = IUPAC.replace(' ', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('[', '')
    IUPAC = IUPAC.replace(']', '')
    IUPAC = IUPAC.replace('{', '')
    IUPAC = IUPAC.replace('}', '')
    IUPAC = IUPAC.replace(',', '')

    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

name 'SMILES' is not defined

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    IUPAC = IUPAC.upper()
    IUPAC = IUPAC.replace('-', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')
    IUPAC = IUPAC.replace('(', '')
    IUPAC = IUPAC.replace(')', '')

    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

name 'SMILES' is not defined

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    IUPAC = IUPAC.upper()
    IUPAC = IUPAC.replace("-", "")
    IUPAC = IUPAC.replace("(", "")
    IUPAC = IUPAC.replace(")", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace(":", "")
    IUPAC = IUPAC.replace(",", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("(", "")
    IUPAC = IUPAC.replace(")", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace(":", "")
    IUPAC = IUPAC.replace(",", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("(", "")
    IUPAC = IUPAC.replace(")", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace(":", "")
    IUPAC = IUPAC.replace(",", "")
    IUPAC = IUPAC.replace("'", "")

    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

name 'SMILES' is not defined

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def iupac2smiles(IUPAC):
    """
    This function takes in the IUPAC name string and converts it to a SMILES string
    """
    IUPAC = IUPAC.upper()
    IUPAC = IUPAC.replace("-", "")
    IUPAC = IUPAC.replace("(", "")
    IUPAC = IUPAC.replace(")", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace(":", "")
    IUPAC = IUPAC.replace(",", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("[", "")
    IUPAC = IUPAC.replace("]", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")
    IUPAC = IUPAC.replace("'", "")

    return SMILES

iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"

result = True if iupac2smiles(iupac) == smiles else False

Output:

name 'SMILES' is not defined

karplusant

Query

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    [insert]
    return J

Run 0

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = A*B*C - phi


|/ file dstars=0 


    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = A*B*C - A*C*B
    J -= A*B*C*B
    J -= A*C*B*B
    J -= A*C*B*C



    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 2

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = A*B*C - A*C*B
    J -= phi*A*B*C
    J -= phi*A*C*B
    J -= phi*A*C*C



    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 3

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = A * np.exp(-B * phi) + C * np.exp(-B * phi)



    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def coupling(phi, A, B, C):
    """
    Returns the J coupling using the karplus equation
    """
    J = A*phi*B*C


|/ file dstars=1 


    return J

import numpy as np

A = 1
B = 2
C = 1
phi = np.pi/7

J = A+B*np.cos(phi)+C*np.cos(2*phi)

J_codex = coupling(phi,A,B,C)

if np.isclose(J, J_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

kld

Query

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  [insert]
  return loss

Run 0

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = 0
  for i in range(len(true_data)):
    loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))



  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 1

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = 0
  for i in range(len(true_data)):
    loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))



  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 2

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = 0
  for i in range(len(true_data)):
    loss += np.log2(true_data[i] + predicted_data[i]) - np.log2(true_data[i] + predicted_data[i])



  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 3

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = 0
  for i in range(len(true_data)):
    loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))



  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

Run 4

import numpy as np

def kld(true_data, predicted_data):
  """
  This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
  """
  loss = 0
  for i in range(len(true_data)):
    loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))



  return loss
import numpy as np

np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
    np.divide(predictions, targets) + 1e-10))

result = True if np.isclose(kld(targets, predictions), kld_loss) else False

Output:

Success

langevin_dynamics

Query

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    [insert]
    return x_traj, v_traj

Run 0

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1,n_steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)



    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

F() takes from 1 to 2 positional arguments but 4 were given

Run 1

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1,n_steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
        



    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

F() takes from 1 to 2 positional arguments but 4 were given

Run 2

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1,n_steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)



    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

F() takes from 1 to 2 positional arguments but 4 were given

Run 3

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    
    for i in range(n_steps):
        x_traj[i] = x0
        v_traj[i] = v0
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

Success

Run 4

import numpy as np

def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
    """
    This function runs a Langevin dynamics simulation in 1d in an external potential
    It returns the trajectory of x and v.

    The initial position is x0
    The initial velocity is v0
    The temperature is T
    m is the mass
    F(x) is a function that returns the external force
    gamma is the drag coefficient
    """
    x_traj = np.zeros(n_steps)
    v_traj = np.zeros(n_steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1,n_steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)



    return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
#    return (q**2-1.0)**2
#def F(q):
#    return -4.0 * q * (q**2-1.0)
def F(q,k=2):
    return -k*q

x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m

result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else False

Output:

F() takes from 1 to 2 positional arguments but 4 were given

weighted-least-squares

Query

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    [insert]
    return beta

Run 0

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.lstsq(x, y, w)[0]


|/



|/

|/



|/

|/

|/

|/

|/


    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

invalid syntax (<string>, line 10)

Run 1

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.lstsq(x, y, w)[0]


|/



|/

|/

|/



|/

|/

|/

|/

|/

|/


    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

invalid syntax (<string>, line 10)

Run 2

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.lstsq(x, y, w)[0]


|/

|/



|/



|/

|/

|/

|/

|/


    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

invalid syntax (<string>, line 10)

Run 3

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.lstsq(x, y, w)[0]


|/



|/

|/

|/

|/

|/

|/

|/

|/



    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

invalid syntax (<string>, line 10)

Run 4

import numpy as np

def lsq(x, y, w):
    ''' Returns fit coefficients from weighted least squares. x should be a matrix.
    '''
    beta = np.linalg.lstsq(x, y, w)[0]


|/



|/

|/

|/

|/

|/

|/

|/

|/


    return beta
import numpy as np
N = 100

x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)

diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
    x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)

beta_hat_m = lsq(x, y, w)

result = np.allclose(beta_hat, beta_hat_m)

Output:

invalid syntax (<string>, line 10)

lipinski_rule_of_five

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    [insert]
    return result

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return False
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

name 'result' is not defined

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)
    mol = Chem.AddHs(mol)

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

name 'result' is not defined

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return False
    hydrogen_bond_donors = mol.GetNumAtoms()
    hydrogen_bond_acceptors = mol.GetNumBonds()
    mol_weight = mol.GetTotalNumAtoms()
    mol_logP = mol.GetTotalNumHs()
    mol_daltons = mol.GetNumDaltons()
    mol_logP_daltons = mol.GetTotalNumHs()
    mol_logP_acceptors = mol.GetTotalNumHs()
    mol_logP_daltons_acceptors = mol.GetTotalNumHs()
    mol_logP_acceptors_daltons = mol.GetTotalNumHs()
    mol_logP_acceptors_daltons_acceptors = mol.GetTotalNumHs()
    mol_logP_acceptors_daltons_acceptors_daltons = mol.GetTotalNumHs()
    mol_logP_acceptors_daltons_acceptors_daltons_daltons = mol.GetTotalNumHs()

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

'Mol' object has no attribute 'GetTotalNumAtoms'

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return False
    
    hydrogen_bonds = [bond for bond in mol.GetBonds() if bond.GetBondType() == Chem.rdchem.BondType.HYDROGEN]
    hydrogen_bonds.sort(key = lambda bond: bond.GetBeginAtomIdx())
    hydrogen_bonds.sort(key = lambda bond: bond.GetEndAtomIdx())
    hydrogen_bonds.sort(key = lambda bond: bond.GetBondType())
    hydrogen_bonds.sort(key = lambda bond: bond.GetSmarts())
    hydrogen_bonds.sort(key = lambda bond: bond.GetTotalNumHs())
    hydrogen_bonds.sort(key = lambda bond: bond.GetDegree())
    hydrogen_bonds.sort(key = lambda bond: bond.GetIsAromatic())
    hydrogen_bonds.sort(key = lambda bond: bond.GetIsAromatic())
    hydrogen_bonds.sort(key = lambda bond: bond.GetIsAromatic())
    hydrogen_bonds.sort(key = lambda bond: bond.GetIsAromatic())

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

name 'result' is not defined

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def lipinski_rule_of_five(smiles):
    """
    This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.

    Lipinski's rules are:
    Hydrogen bond donors <= 5
    Hydrogen bond acceptors <= 10
    Molecular weight < 500 daltons
    logP < 5
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)

    return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'  # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)

if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
    passed = True
else:
    passed = False

result = True if lipinski_rule_of_five(smiles) == passed else False

Output:

name 'result' is not defined

mape

Query

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  [insert]
  return e

Run 0

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = y_hat - y


|/





|/







  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

invalid syntax (<string>, line 12)

Run 1

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = y_hat - y




|/



|/

|/


  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

invalid syntax (<string>, line 14)

Run 2

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = y_hat - y




|/



|/



|/



  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

invalid syntax (<string>, line 14)

Run 3

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = 0
  for i in range(len(y_hat)):
    e += abs(y_hat[i] - y[i])




|/

|/


  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

invalid syntax (<string>, line 16)

Run 4

import math
import sys

def mape(y_hat,y):
  """
  This function computes the mean absolute percentage error (mape) between y_hat and y.
  """
  e = y_hat - y




|/


  return e
import numpy as np

np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))

test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else False

Output:

invalid syntax (<string>, line 14)

mapping_operator

Query

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  [insert]
  return M

Run 0

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = []
  for bead, mapping in beads_mappings.items():
    atom_selection = molecule.selectAtomsByBonds(bead)
    atom_selection_length = len(atom_selection)
    atom_selection_weights = np.ones(atom_selection_length) / atom_selection_length
    atom_selection_weights[atom_selection] = mapping
    M.append(atom_selection_weights)


|/

|/


  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

invalid syntax (<string>, line 19)

Run 1

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((molecule.n_atoms, molecule.n_atoms))
  for i in range(molecule.n_atoms):
    for j in range(molecule.n_atoms):
      M[i][j] = beads_mappings[i][j]


|/


  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

invalid syntax (<string>, line 16)

Run 2

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((len(beads_mappings), len(beads_mappings)))
  for i in range(len(beads_mappings)):
    for j in range(len(beads_mappings)):
      M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i]).GetAtomWithIdx(beads_mappings[j]).GetDegree()


|/


  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

invalid syntax (<string>, line 16)

Run 3

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((len(beads_mappings), len(beads_mappings)))
  for i, beads_mapping in enumerate(beads_mappings):
    for j, beads_mapping in enumerate(beads_mappings):
      M[i][j] = beads_mapping
  M = np.transpose(M)


|/


  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

invalid syntax (<string>, line 17)

Run 4

import MDAnalysis
import numpy as np

def mapping_operator(molecule, beads_mappings):
  """
  This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
  and atom selections for the beads.
  """
  M = np.zeros((molecule.n_atoms, molecule.n_atoms))
  for i in range(molecule.n_atoms):
    for j in range(molecule.n_atoms):
      M[i][j] = beads_mappings[i][j]


|/


  return M
import numpy as np
import MDAnalysis as mda
import os

# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
    for i, atom in enumerate(beads_mappings[s]):
        CG_matrix[s, i + index] = [v for k,
                                   v in Mws_dict.items() if atom in k][0]
    index += np.count_nonzero(CG_matrix[s])
    CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])

result = True if np.isclose(
    CG_matrix, mapping_operator(molecule, beads_mappings)).all() else False

Output:

invalid syntax (<string>, line 16)

matpow

Query

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  [insert]
  return r

Run 0

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.zeros(x.shape)
  r[n:] = x
  r[n:,n:] = x
  r[:,n:] = x






  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

could not broadcast input array from shape (2,2) into shape (0,2)

Run 1

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.power(x,n)












  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 2

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.power(x,n)














  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 3

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.power(x,n)














  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

Run 4

import numpy as np

def matpow(x,n):
  """
  This function computes matrix x raised to the power n.
  """
  r = np.power(x,n)








  return r
import numpy as np


x = np.array([[0, 1], [-1, 0]])

true_y = np.linalg.matrix_power(x,3)

pred_y = matpow(x,3)

result = True if np.allclose(true_y,pred_y) else False

Output:

Success

matrix_factorial

Query

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     [insert]
     return f

Run 0

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.matrix(np.zeros((n,n)))
     for i in range(n):
         for j in range(n):
             f[i,j] = f[j,i]*i



     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

only integer scalar arrays can be converted to a scalar index

Run 1

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.matrix(np.zeros((n,n)))
     for i in range(n):
         for j in range(n):
             f[i,j] = f[j,i]*i


|/


     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

invalid syntax (<string>, line 14)

Run 2

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.zeros((n, n))
     for i in range(n):
         for j in range(n):
             f[i, j] = f[i, j] * i



     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

only integer scalar arrays can be converted to a scalar index

Run 3

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     f = np.matrix(np.zeros((n,n)))
     for i in range(n):
         for j in range(n):
             f[i,j] = f[j,i]*i



     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

only integer scalar arrays can be converted to a scalar index

Run 4

import numpy as np

def matrix_factorial(n):
     """
     This function calculates and returns the factorial of a matrix (array) element wise
     """
     if n == 0:
         return 1
     else:
         return n * matrix_factorial(n - 1)


     return f

import numpy as np

x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])

result = np.array_equal(x_f,m_f) 

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

max-boltz

Query

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   [insert]
   return s

Run 0

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   s = math.sqrt(T*M/1000)


|/


   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 15)

Run 1

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   s = math.sqrt(T*M*M)/1000


|/


   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 15)

Run 2

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   s = math.sqrt(M*T/1000)


|/


   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 15)

Run 3

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   s = math.sqrt(T*M/1000)


|/


   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 15)

Run 4

import math
import sys

def max_boltz_rms_speed(T,M):
   """
   This function returns the rms speed of a molecule in m/s

   The temperature is T in Kelvin
   The molecule has mass M in kiolograms
   """
   s = math.sqrt(T/M)


|/


   return s
import numpy as np

# input params
M = 32e-3           # for O2, kg/mol
R = 8.314           # J/mol.K
T = 300

c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)

M_in_kg = M/6.022e23

c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)

# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 15)

michaelis

Query

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   [insert]
   return v

Run 0

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * math.exp(-S/Km)
   
   



   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * S * math.exp(-Km * S)
   
   



   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax
   for t in range(1,S+1):
      v = v * (Km * (t/S) + 1/(S*math.exp(-t/S)))
   
if __name__ == "__main__":
   Vmax = int(sys.argv[1])
   S = int(sys.argv[2])
   Km = float(sys.argv[3])
   print(reaction_velocity(Vmax, S, Km))




   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

'return' outside function (<string>, line 22)

Run 3

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * S * math.exp(-Km * S)
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def reaction_velocity(Vmax, S, Km):
   """
   This function returns the initial reaction rate according to Michaelis-Menten kinetics
   """
   v = Vmax * math.exp(-S * Km)



   return v

import numpy as np

Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)

v_codex = reaction_velocity(Vmax, S, K_M)

# check 
if np.isclose(v, v_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

mol_charge

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    [insert]
    return charge

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)


    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)


    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    charge = 0
    for atom in Chem.MolFromSmiles(smiles):
        charge += atom.GetTotalNumHs()


    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

'Mol' object is not iterable

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)


    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def net_charge(smiles):
    """
    This function returns net charge of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)


    return charge

s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else False

Output:

Success

net_charge

Query

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    [insert]
    return charge

Run 0

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for c in sequence:
        charge += c



    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

unsupported operand type(s) for +=: 'int' and 'str'

Run 1

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for char in sequence:
        charge += math.log10(float(char))












    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

could not convert string to float: 'D'

Run 2

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for c in sequence:
        charge += math.log10(abs(ord(c) - 97))




|/







    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

invalid syntax (<string>, line 16)

Run 3

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for c in sequence:
        charge += ord(c) - ord('A')


    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

Run 4

import math
import sys

def net_charge(sequence):
    """
    This function returns net charge of amino acid sequence
    """
    charge = 0
    for c in sequence:
        charge += ord(c) - ord('A')



    return charge

result = True if net_charge("DSAVRCPQD") == -1 else False

Output:

Success

solve_ode

Query

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    [insert]
    return sol

Run 0

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = np.zeros(len(t))
    sol[0] = y0
    for i in range(1, len(t)):
        sol[i] = sol[i-1] + fn(t[i-1],sol[i-1])



    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

setting an array element with a sequence.

Run 1

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = []
    for t in t:
        sol.append(fn(t,y0))



    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

can't multiply sequence by non-int of type 'float'

Run 2

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = np.zeros(len(t))
    sol[0] = y0
    for i in range(1, len(t)):
        sol[i] = sol[i-1] + fn(t[i],sol[i-1])



    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

setting an array element with a sequence.

Run 3

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = np.zeros(len(t))
    for i in range(len(t)):
        sol[i] = fn(t[i],y0)



    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

can't multiply sequence by non-int of type 'float'

Run 4

import numpy as np

def solve_ode(fn, t, y0):
    """
    Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
    """
    sol = []
    for t in t:
        sol.append(fn(t,y0))



    return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y): 
    return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])

result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else False

Output:

can't multiply sequence by non-int of type 'float'

ohe

Query

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  [insert]
  return v

Run 0

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros(len(a), dtype=np.int)




|/


  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

invalid syntax (<string>, line 14)

Run 1

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros(len(a), dtype=np.int32)




|/



  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

invalid syntax (<string>, line 14)

Run 2

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros(len(a), dtype=np.int32)


|/ file dstars=0 

|/



|/



|/

|/


  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

invalid syntax (<string>, line 12)

Run 3

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros(len(a), dtype=np.int32)




|/v



  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

invalid syntax (<string>, line 14)

Run 4

import numpy as np

def ohe(a):
  """
  This function generates one-hot encodings for
  the class names in the given list of strings.
  """
  v = np.zeros(len(a), dtype=np.int32)




|/





  return v
import numpy as np

dog_breeds = ['German Shepherd', 'Husky',
              'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']

unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
        ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
        j += 1

result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else False

Output:

invalid syntax (<string>, line 14)

osmotic_pressure

Query

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   [insert]
   return p

Run 0

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = 0.0
   for k in range(1,T+1):
      p = p + R*math.pow(T,k)/math.pow(Pi,k)





   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

math range error

Run 1

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = R*math.pow(T,3.0/4.0)


|/


   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

invalid syntax (<string>, line 15)

Run 2

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = R*math.pow(T,3.0/3.0)
   p = p*math.pow(Pi,3.0/3.0)





   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 3

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = 0.0254 # atm /mol
   rho = 1.225 # atm /mol
   rho_s = rho * math.pow(10,-6)
   rho_m = rho * math.pow(10,-4)
   rho_l = rho * math.pow(10,-2)
   rho_h = rho * math.pow(10,-1)
   rho_d = rho * math.pow(10,0)
   rho_h = rho * math.pow(10,1)
   rho_d = rho * math.pow(10,2)
   rho_h = rho * math.pow(10,3)
   rho_d = rho * math.pow(10,4)
   rho_h = rho * math.pow(10,5)
   rho_d = rho * math.pow(10,6)
   rho_h = rho * math.pow(10,7)
   rho_d = rho * math.pow(10,8)
   rho_h = rho * math.pow(10,9)
   rho_d = rho * math.pow(10,10)
   rho_h = rho * math.pow(10,11)
   rho_d = rho * math.pow(10,12)
   rho_h = rho * math.pow(10,13)
   rho_d = rho * math.pow(10,14)
   rho_h = rho * math.pow(10,15)

   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

Run 4

import math
import sys

def osmotic_pressure_concentration(Pi,T):
   """
   This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
   T is in K
   Pi is in atm
   """
   R = 0.08206 # l atm /K /mol
   p = R*math.pow(T,3.0/4.0)
   p = p*math.pow(Pi,3.0/4.0)







   return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K 
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else False

Output:

Success

pair_wise

Query

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  [insert]
  return distances

Run 0

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  pdb = md.load(pdb_file)
  alpha_carbons = pdb.select('name *[name!= "Carbon"]')
  alpha_carbons = alpha_carbons.sort('name')
  alpha_carbons = alpha_carbons.unique()
  alpha_carbons = list(alpha_carbons)
  distances = []
  for alpha_carbon in alpha_carbons:
    alpha_carbon = alpha_carbon.split()
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split("_")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split("-")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split("+")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split("(")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split(")")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]
    alpha_carbon = alpha_carbon.split(":")
    alpha_carbon = alpha_carbon[0]
    alpha_carbon = alpha_carbon[1:]

  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  pdb = md.load(str(pdb_file))
  alpha_carbons = pdb.select('name *[name!= "Carbon"]')
  alpha_carbons = alpha_carbons.sort('name')
  alpha_carbons = alpha_carbons.unique()
  alpha_carbons = list(alpha_carbons)
  distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
  for i in range(len(alpha_carbons)):
    for j in range(len(alpha_carbons)):
      distances[i][j] = len(alpha_carbons.intersection(alpha_carbons[j]))



  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  pdb = md.load(str(pdb_file))
  alpha_carbons = pdb.select('name *[name!= "Carbon"]')
  alpha_carbons = alpha_carbons.unique()
  alpha_carbons.sort()
  alpha_carbons_length = len(alpha_carbons)
  distances = np.zeros(alpha_carbons_length)
  for i in range(alpha_carbons_length):
    distances[i] = pdb.distances[alpha_carbons[i]]



  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  pdb = pd.read_pdb(pdb_file)

  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md
import numpy as np

def pairwise_dist(pdb_file):
  """
  1 This function loads a pdb
  2 Selects only the alpha carbons
  3 Calculates the number of unique alpha carbon pairs
  4 Returns the distances between each alpha carbon pair
  """
  pdb = md.load(str(pdb_file))
  alpha_carbons = pdb.select("name *[name=*alpha]")
  alpha_carbons = alpha_carbons.sort("name")
  alpha_carbons = alpha_carbons.unique()
  alpha_carbons = list(alpha_carbons)
  alpha_carbons.sort()
  distances = []
  for alpha_carbon in alpha_carbons:
    distances.append(pdb.distances[alpha_carbon])



  return distances
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")


def pairwise(pdb_file):
    import mdtraj as md
    from itertools import combinations
    pdb = md.load(pdb_file)
    cas = pdb.top.select("name CA")
    distances = []
    comb = combinations(cas, 2)
    distances = md.compute_distances(pdb, comb, periodic=True)
    return distances


my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)

#print("My result:", my_result)
#print("nlcc result", nlcc_result)

result = True if np.abs(np.mean(my_result) -
                        np.mean(nlcc_result)) < 0.01 else False

Output:

'Constant' object has no attribute 'kind'

pauli_matrices

Query

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    [insert]
    return sigma_x, sigma_y, sigma_z

Run 0

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = 1
    sigma_y = 1
    sigma_z = 1



    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 1

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = 1
    sigma_y = 1
    sigma_z = 1



    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 2

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = 1
    sigma_y = 1
    sigma_z = 1



    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 3

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = 1
    sigma_y = 1
    sigma_z = 1



    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

Run 4

import numpy as np

def pauli():
    """
    This function returns the three pauli matrices
    """
    sigma_x = 1
    sigma_y = 1
    sigma_z = 1



    return sigma_x, sigma_y, sigma_z


sx = np.array(((0,1),(1,0)))
sy = np.array(((0,-1j),(1j,0)))
sz = np.array(((1,0),(0,-1)))

sx_codex, sy_codex, sz_codex = pauli()
result = np.all(sx==sx_codex)*np.all(sy==sy_codex)*np.all(sz==sz_codex)

Output:

Success

pi

Query

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    [insert]
    return pi_est

Run 0

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    pi_est = 2 * np.pi * nsamples / nsamples




|/|/|/


    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    pi_est = 1.
    for _ in range(nsamples):
        pi_est *= 1.



    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

Success

Run 2

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    pi_est = 2*np.pi*np.random.random(nsamples)




|/|/


    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

invalid syntax (<string>, line 11)

Run 3

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    pi_est = np.pi
    pi_est *= nsamples




|/|/



    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

invalid syntax (<string>, line 12)

Run 4

import numpy as np

def pi(nsamples):
    """ This function returns the value of pi by monte carlo sampling """
    pi_est = 1.
    for i in range(nsamples):
        pi_est *= 1.




|/

|/

|/


    return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else False

Output:

invalid syntax (<string>, line 13)

pib_1d

Query

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   [insert]
   return e

Run 0

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e=n*(m*L**2-L**2-hbar*hbar*hbar)


   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 1

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e=n-m*L*hbar
   return e


   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

Run 2

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e=math.exp(-0.5*((n-m)/L)*hbar)


|/ file dstars=0 





   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

invalid syntax (<string>, line 12)

Run 3

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e=math.exp(-0.5*((n-m)/L))
   e=e*hbar




|/

|/

|/


   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

invalid syntax (<string>, line 15)

Run 4

import math
import sys

def particle_in_box(n,m,L,hbar=1):
   """
   This function returns the energy for a quantum particle in a 1d box
   """
   e=n*(m*L**2+hbar*L**3)
   return e


   return e
import numpy as np
import matplotlib.pyplot as plt

# input params 
L = 10     # length of the box
m = 1      # masss of the particle
n = 10     # quantum number 
hbar = 1      # planck constant

# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)

e_n_codex = particle_in_box(n,m,L)  
print("energy from codex =", e_n_codex)


# check
if abs(e_n - e_n_codex) <= 1e-3:
    result = True 
else:
    result = False



Output:

Success

pred_interval

Query

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   [insert]
   return n

Run 0

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = len(p)
   for i in range(n):
      if p[i]  pred_level:
         return i


   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

invalid syntax (<string>, line 10)

Run 1

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = int(np.floor(np.log(p) / np.log(pred_level)))


|/ file dstars=0 

|/

|/



|/

|/


   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

invalid syntax (<string>, line 11)

Run 2

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = int(np.log2(pred_level))


|/



   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

invalid syntax (<string>, line 11)

Run 3

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = int(np.floor(np.log(p)/np.log(pred_level)))




|/

|/


   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

invalid syntax (<string>, line 13)

Run 4

import numpy as np

def num_trials(pred_level, p):
   """Returns the minimum number of trials needed to achieve
      a probability given by pred_level in a geometric distribution
   """
   n = len(p)
   for i in range(n):
      p[i] = p[i] / np.sum(p[i])






   return n
import numpy as np

prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
    psum += (1 - p) ** (n - 1) * p
    if(psum >= prediction_level):
        break

result = True if num_trials(prediction_level, p) == n else False

Output:

object of type 'float' has no len()

pubchem

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  [insert]
  return mols

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'http://rest.pubchem.net/api/similarity?smiles=%s&format=smiles' % smiles
  response = requests.get(url)
  data = response.json()
  mols = data['results']
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]

  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N)&format=smiles (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffbbfc7e520>: Failed to establish a new connection: [Errno -2] Name or service not known'))

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'http://rest.pubchem.net/api/similarity?smiles=' + smiles
  response = requests.get(url)
  data = response.json()
  mols = []
  for mol in data['results']:
    mols.append(Chem.MolFromSmiles(mol))
  return mols


  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N) (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffbbfccbee0>: Failed to establish a new connection: [Errno -2] Name or service not known'))

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'http://rest.pubchem.net/api/similarity?query={}&format=smiles'.format(smiles)
  response = requests.get(url)
  smiles = response.text
  mols = Chem.MolFromSmiles(smiles)
  mols = [Chem.MolToSmiles(mol) for mol in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]
  mols = [Chem.MolFromSmiles(smi) for smi in mols]

  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?query=CC=C=C(C(=O)N)&format=smiles (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffbbfcf0d00>: Failed to establish a new connection: [Errno -2] Name or service not known'))

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search"
  payload = {
    "query": smiles,
    "limit": 10,
    "format": "smi",
    "sort": "similarity",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",
    "format": "smi",

  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

invalid syntax (<string>, line 63)

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

import requests

def find_similar(smiles):
  """
  Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
  The returned molecules are SMILES strings, not CIDs.
  """
  url = 'http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/similarity?smiles=%s&format=sdf'
  url = url % smiles
  response = requests.get(url)
  smiles = response.text
  mols = Chem.MolFromSmiles(smiles)
  mols = Chem.AddHs(mols)
  mols = Chem.RemoveHs(mols)
  mols = Chem.RemoveAtoms(mols, rdMolHash.HashedAtom)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAtomPositions)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAtomTypes)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAromaticRings)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAromaticSites)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAromaticRings)
  mols = Chem.RemoveAtoms(mols, Scaffolds.All.GetAromaticSites)

  return mols
import requests
import time

time.sleep(0.5)


def ref_find_similar(s):
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
    reply = requests.get(
        url,
        params={"Threshold": 80, "MaxRecords": 100},
        headers={"accept": "text/json"},
        timeout=10,
    )
    data = reply.json()
    smiles = [d["CanonicalSMILES"]
              for d in data["PropertyTable"]["Properties"]]
    smiles = set(smiles)
    return smiles


s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else False

Output:

Python argument types in
    rdkit.Chem.rdmolops.AddHs(NoneType)
did not match C++ signature:
    AddHs(RDKit::ROMol mol, bool explicitOnly=False, bool addCoords=False, boost::python::api::object onlyOnAtoms=None, bool addResidueInfo=False)

pyscf_energy

Query

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    [insert]
    return ground_energy

Run 0

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mol.verbose = 0
    mol.output = None
    mol.atom = [['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

invalid syntax (<string>, line 28)

Run 1

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mol.verbose = 5
    mol.output = '/dev/null'
    mol.atom = [['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

invalid syntax (<string>, line 28)

Run 2

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.Mole()
    mol.atom = atom
    mol.basis = basis
    mol.charge = 0
    mol.spin = 0
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.build()
    mol.verbose = 0

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

'NoneType' object has no attribute 'write'

Run 3

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mol.build()
    mol.verbose = 5
    mol.output = None
    mol.atom = [['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

invalid syntax (<string>, line 29)

Run 4

import pyscf
import numpy as np

def calc_molecule_energy(atom,basis):
    """
    This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
    """
    mol = pyscf.gto.M(atom=atom,basis=basis)
    mol.build()
    mol.verbose = 0
    mol.output = None
    mol.atom = [['H', (0., 0.    , 0.)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],
                ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757 , 0.587)],

    return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"

#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf

def calc_molecule_energy_test(atom_coordinates,basis):
    mol = gto.M(atom=atom_coordinates,basis=basis)
    mf = scf.RHF(mol)
    return mf.kernel()

my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)

print("My result:", my_energy)
print("nlcc result:", nlcc_energy)

result = True if np.abs( my_energy - nlcc_energy )<0.1 else False

Output:

invalid syntax (<string>, line 29)

qed

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    [insert]
    return result

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)

    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

name 'result' is not defined

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)

    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

name 'result' is not defined

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.MolToSmiles(mol)
    mol = Chem.MolFromSmiles(smiles)

    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

name 'result' is not defined

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(0))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(1))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(2))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(3))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(4))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(5))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(6))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(7))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(8))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(9))
    mol = Chem.RemoveAtoms(mol, Chem.AtomWithIdx(10))

    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

module 'rdkit.Chem' has no attribute 'RemoveAtoms'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def qed(smiles):
    """
    This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
    """
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)
    mol = Chem.RemoveHs(mol)

    return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)

result = True if np.isclose(qed(smiles), q) else False 

Output:

name 'result' is not defined

quantile

Query

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  [insert]
  return result

Run 0

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.zeros_like(a)
  result[np.where(aq)[0]] = np.nan




|/|/|/


  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

invalid syntax (<string>, line 14)

Run 1

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.zeros_like(a)
  result[np.where(a=q)] = a[np.where(a=q)]
=q)]



  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

invalid syntax (<string>, line 10)

Run 2

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.zeros_like(a)
  result[np.where(a=q)] = a[(q=a) & (a=q+1)]
=q-1)]



  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

invalid syntax (<string>, line 9)

Run 3

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.zeros_like(a)
  result[np.where(a=q)] = a[np.where(a=q)]
q)]



  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

unmatched ')' (<string>, line 10)

Run 4

import numpy as np

def quantile(a, q):
  """
  This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
  """
  result = np.zeros_like(a)
  result[np.where(a=q)] = a[np.where(a=q)]
q)]



  return result
import numpy as np

np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]

result = True if np.allclose(
    quantile(data, quantiles), np.quantile(data, q=quantiles)) else False

Output:

unmatched ')' (<string>, line 10)

random_walk

Query

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    [insert]
    return traj

Run 0

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = []
    for i in range(N):
        x1 = x0 + a * np.random.rand()
        x2 = x1 + a * np.random.rand()
        x3 = x2 + a * np.random.rand()
        traj.append([x0, x1, x2, x3])
        x0 = x1



    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Run 1

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = []
    for i in range(N):
        x1 = x0 + a * np.random.randn(1)
        traj.append([x0, x1])
        x0 = x1



    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

loop of ufunc does not support argument 0 of type numpy.ndarray which has no callable log method

Run 2

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = []
    for i in range(N):
        x1 = x0 + a * np.random.randn()
        traj.append([x1, x0])
        x0 = x1


|/ file dstars=0 


    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

invalid syntax (<string>, line 17)

Run 3

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = []
    for i in range(N):
        x1 = x0 + a * np.random.rand()
        traj.append([x1, x0])
        x0 = x1



    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Run 4

import numpy as np

def random_walk(N):
    """
    This function returns the trajectory of an N step random walk on a one dimensional lattice
    """
    a = 1 # lattice spacing
    x0 = 0
    traj = []
    for i in range(N):
        x1 = x0 + a * np.random.randn()
        traj.append([x0, x1])
        x0 = x1





    return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
    nlcc_trj = random_walk(nsteps)
    nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)

msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)

a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)

#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else False

Output:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

rank

Query

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    [insert]
    return r

Run 0

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, S, V = np.linalg.svd(M)
    rank = S.shape[0]
    return rank


    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 1

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    u, s, v = np.linalg.svd(M)
    rank = np.linalg.matrix_rank(M)
    return rank


    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

Success

Run 2

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, S, V = np.linalg.svd(M)
0)[0]




|/|/

|/


    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

unmatched ')' (<string>, line 9)

Run 3

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U,S,V = np.linalg.svd(M)
    r = np.argsort(np.abs(S))




|/

|/




    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

invalid syntax (<string>, line 14)

Run 4

import numpy as np

def rank(M):
    """
    This function calculates the rank of matrix M using singular value decomposition.
    """
    U, s, V = np.linalg.svd(M)
    rank = s.argmax()




|/

|/

|/


    return r
import numpy as np

np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)

result = True if np.isclose(r, rank(M)) else False

Output:

invalid syntax (<string>, line 14)

remove-water

Query

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  [insert]
  return new_traj

Run 0

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  new_traj = md.load(traj_file)
  new_traj.top = md.load(top_file)



  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

"top" argument is required for load_trr

Run 1

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file)
  top = md.load(top_file)
  traj = traj.rename_keys({'topology':'topology_new'})
  top = top.rename_keys({'topology':'topology_new'})
  new_traj = traj.topology.remove_solvent_from_topology(top)



  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

"top" argument is required for load_trr

Run 2

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file)
  top = md.load(top_file)
  new_traj = traj.remove_solvent_from_topology(top)



  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

"top" argument is required for load_trr

Run 3

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  new_traj = md.load(traj_file)
  new_traj.top = md.load(top_file)



  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

"top" argument is required for load_trr

Run 4

import mdtraj as md
import numpy as np

def remove_water(traj_file,top_file):
  """
  This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
  """
  traj = md.load(traj_file)
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology
  traj = traj.remove_solvent_atoms('water')
  traj = traj.topology

  return new_traj
import os
import mdtraj as md 

traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False 

Output:

"top" argument is required for load_trr

rms_velocity

Query

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   [insert]
   return v_rms

Run 0

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   v_rms = math.sqrt(m*T*T/m)
   
   



   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   v_rms = math.sqrt(T*T/(m*m))



   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   v_rms = math.sqrt(T*m*m/3.0)



   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 3

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   v_rms = math.sqrt(T*m*m/T)
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def rms_velocity(T,m):
   """
   This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
   m is mass in g/mol
   """
   v_rms = math.sqrt(T*m*m/3.0)



   return v_rms

import numpy as np

m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))

v_rms_codex = rms_velocity(T,m)

# check 
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

rmse

Query

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  [insert]
  return e

Run 0

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.square(a-b).mean()


|/







  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt((a-b)**2)


|/







  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

invalid syntax (<string>, line 11)

Run 2

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt((a-b)**2)


|/

|/ file dstars=0 











  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

invalid syntax (<string>, line 11)

Run 3

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt((a-b)**2).mean()




|/

|/







  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

invalid syntax (<string>, line 13)

Run 4

import numpy as np

def rmse(a,b):
  """
  This function evaluates the root mean square error (rmse) between a and b.
  """
  e = np.sqrt((a-b)**2).mean()


|/









  return e
import numpy as np

np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))

test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else False

Output:

invalid syntax (<string>, line 11)

rog

Query

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  [insert]
  return rg

Run 0

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  pdb = md.load(pdb_file)
  rg = mdtraj.distances.compute_radius_of_gyration(pdb)




|/


  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

invalid syntax (<string>, line 17)

Run 1

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  pdb = md.load(pdb_file)
  rg = protein_radius(pdb)
  return rg


  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

name 'protein_radius' is not defined

Run 2

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  pdb = md.load(pdb_file)
  rg = mdtraj.distances.distance(pdb, 'A', 'R')





  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

name 'mdtraj' is not defined

Run 3

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  pdb = md.load(pdb_file)
  rg = md.get_geom_property(pdb, 'name', 'rg')





  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

module 'mdtraj' has no attribute 'get_geom_property'

Run 4

import mdtraj as md
import numpy as np

def protein_radius_of_gyration(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the radius of gyration
  3. Returns it
  """
  pdb = md.load(pdb_file)
  rg = protein_radius(pdb)



  return rg
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_rg_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    rg = md.compute_rg(pdb)
    return rg

my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)

#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)

result = True if np.abs( my_rg - nlcc_rg )<0.1 else False

Output:

name 'protein_radius' is not defined

rotationant

Query

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    [insert]
    return E_rot

Run 0

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = 0
    for j in range(J.shape[0]):
        E_rot += B[j]*np.exp(-1j*B[j]*J[j])



    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object has no attribute 'shape'

Run 1

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = 0
    for j in range(J.shape[0]):
        E_rot += B[j]*np.exp(-B[j]*J[j])



    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object has no attribute 'shape'

Run 2

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = 0
    for k in range(J.shape[0]):
        E_rot += B[k]*np.conj(B[k])



    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object has no attribute 'shape'

Run 3

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = 0
    for k in range(J.shape[0]):
        E_rot += B[k]*np.conj(B[k])



    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object has no attribute 'shape'

Run 4

import numpy as np

def e_rot(B,J):
    """
    Returns the quantum rotational energy for level J and constant B
    """
    E_rot = B*J


|/ file dstars=1 

    return E_rot

import numpy as np

B = 2
J = 3

E_rot = B*J*(J+1)

E_rot_codex = e_rot(B,J)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

invalid syntax (<string>, line 11)

rotation_higherant

Query

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    [insert]
    return E_rot

Run 0

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = B*J*D



    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 1

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = 0
    for k in range(J):
        E_rot += B[k]*D[k]



    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object is not subscriptable

Run 2

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = 0
    for k in range(J):
        E_rot += B[k]*(D[k]*B[k])



    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object is not subscriptable

Run 3

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = 0
    for k in range(J):
        E_rot += B*D*k



    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

Success

Run 4

import numpy as np

def e_rot(B,J,D):
    """
    Returns the quantum rotational energy for level J and constants B, D
    """
    E_rot = 0
    for j in range(J):
        E_rot += B[j]*D[j]



    return E_rot

import numpy as np

B = 2
J = 3
D = 2

E_rot = B*J*(J+1) - D*(J**2)*((J+1)**2)

E_rot_codex = e_rot(B,J,D)

if np.isclose(E_rot, E_rot_codex) ==  True:
    result = True
else:
    result = False

Output:

'int' object is not subscriptable

sasa

Query

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  [insert]
  return sasa

Run 0

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  pdb = md.load(pdb_file)
  sasa = pdb.select('CA', resname='CA')


|/


  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

invalid syntax (<string>, line 15)

Run 1

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  pdb = mdtraj.load(pdb_file)
  sasa = []
  for residue in pdb.residues:
    sasa.append(residue.solvent_accessible_surface_area)



  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

name 'mdtraj' is not defined

Run 2

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  pdb = md.load(pdb_file)
  sasa = pdb.select('CA')
  sasa.rename("CA")


|/


  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

invalid syntax (<string>, line 16)

Run 3

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  pdb = md.load(pdb_file)
  sasa = pdb.select('CA')


|/


  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

invalid syntax (<string>, line 15)

Run 4

import mdtraj as md
import numpy as np

def protein_surface_area(pdb_file):
  """
  1. This function loads a pdb
  2. Calculates the Solvent Accessible Surface Area (sasa) per residue
  3. Returns it
  """
  pdb = md.load(pdb_file)
  sasa = pdb.select('CA')
  sasa = sasa.sum(axis=1).sum(axis=1)


|/


  return sasa
import numpy as np
import sys
import os

pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")

def compute_sasa_mdtraj(pdb_file):
    import mdtraj as md
    pdb = md.load(pdb_file)
    
    sasa = md.shrake_rupley(pdb,mode='residue')
    return sasa

my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)

#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)

result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else False

Output:

invalid syntax (<string>, line 16)

scaffold

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    [insert]
    return scaffold_smiles

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))


    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold = Scaffolds.MurckoScaffold()
    scaffold.Compute2DCoords(mol)
    return scaffold.GetMol()


    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold_smiles = Chem.MolToSmiles(mol)


    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    mol = Chem.MolFromSmiles(smiles)
    scaffold = Scaffolds.MurckoScaffold()
    scaffold.Compute2DCoords(mol)
    return scaffold.GetMol()


    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def scaffold(smiles):
    """
    Returns Murcko scaffold of given molecule
    """
    scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))


    return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
    mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == sc

Output:

Success

seq-align

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    [insert]
    return aligned

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))], gap_char="-")
    return aln.get_alignment_dict()


    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

name 'SeqRecord' is not defined

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    aln = AlignIO.read("%s.aln" % seq1, "fasta")
    aln = AlignIO.read("%s.aln" % seq2, "fasta")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")
    aln = AlignIO.read("%s.aln" % seq2, "pdb")
    aln = AlignIO.read("%s.aln" % seq1, "pdb")

    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

name 'AlignIO' is not defined

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
    aln.set_flags(aln.get_flags() | Align.DONT_OVERLAP)
    aln.set_residue_as_bits()
    aln.set_score_as_bits()
    aln.set_query_name(seq1)
    aln.set_target_name(seq2)
    return AlignIO.read(aln, "clustal")


    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

__init__() got an unexpected keyword argument 'gap_char'

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    aln = AlignIO.read("blastn", "blastn")
    aln = AlignIO.parse(aln, "blastn")
    aln = aln.align(seq1, seq2)
    aln = aln.reverse_complement()
    aln = aln.seq
    aln = Seq(aln)
    return aln


    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

name 'AlignIO' is not defined

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def align(seq1, seq2):
    '''
    Align the two amino acid sequences with BLOSUM62 and return aligned sequences
    '''
    aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
    aln.set_scorer(lambda a: a.alignment_score)
    return aln


    return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'

Output:

__init__() got an unexpected keyword argument 'gap_char'

seq-trans

Query

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  [insert]
  return prot_seq

Run 0

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq)


  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 1

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq)



  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 2

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq)


  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 3

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq)


  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

Run 4

from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist

def nucleotide_translate(gene_seq):
  """
  Converts nucleotide sequence to amino acids. Returns a string
  """
  prot_seq = Seq(gene_seq)


  return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tps

Output:

Success

sequence

Query

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    [insert]
    return x

Run 0

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

name 'x' is not defined

Run 1

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    
    x = np.arange(s)
    
    
    
    








|/


    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

invalid syntax (<string>, line 22)

Run 2

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    
    seq = []
    
    for i in range(s):
        seq.append(i)
    
    for i in range(e):
        seq.append(i)
    
    for i in range(l):
        seq.append(i)
    
    return seq


    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

Success

Run 3

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    
    x = np.arange(s,e+1,1)
    
    
    
    






|/

|/x


    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

invalid syntax (<string>, line 20)

Run 4

import numpy as np

def gen_geometric_sequence(s,e,l):
    """
    This function return a geometric sequence that starts at s, ends at e with length l
    """
    
    s=np.float(s)
    e=np.float(e)
    l=int(l)
    
    x=np.linspace(s,e,l)
    




|/

|/

|/


    return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else False

Output:

invalid syntax (<string>, line 19)

sle

Query

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  [insert]
  return x

Run 0

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  eqns = sympy.sympify(eqns)
  x = sympy.symbols('x')
  eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0',real=True)})
  eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1',real=True)})
  eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0',imaginary=True)})
  eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1',imaginary=True)})
  eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0',complex=True)})
  eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1',complex=True)})

  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

Run 1

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  eqns = sympy.sympify(eqns)
  a = eqns.subs({sympy.Symbol('a_0'): 0, sympy.Symbol('a_1'): 0})
  b = eqns.subs({sympy.Symbol('b_0'): 0, sympy.Symbol('b_1'): 0})
  c = eqns.subs({sympy.Symbol('c_0'): 0, sympy.Symbol('c_1'): 0})
  d = eqns.subs({sympy.Symbol('d_0'): 0, sympy.Symbol('d_1'): 0})
  x = sympy.solve([a,b,c,d], sympy.Symbol('x'))


|/


  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

invalid syntax (<string>, line 16)

Run 2

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.symbols('x')
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn[0], eqn[1]) for eqn in eqns]

  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

SympifyError: '4'

Run 3

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.symbols('x')
  eqns = eqns.replace(' ', '')
  eqns = eqns.replace('[', '')
  eqns = eqns.replace(']', '')
  eqns = eqns.replace('=', '')
  eqns = eqns.replace(',', '')
  eqns = eqns.replace('(', '')
  eqns = eqns.replace(')', '')
  eqns = eqns.replace('^', '')
  eqns = eqns.replace('_', '')
  eqns = eqns.replace('+', '')
  eqns = eqns.replace('=', '')
  eqns = eqns.replace('x', 'x_0')
  eqns = eqns.replace('x_0', 'x_1')
  eqns = eqns.replace('x_1', 'x_2')
  eqns = eqns.replace('x_2', 'x_3')
  eqns = eqns.replace('x_3', 'x_4')
  eqns = eqns.replace('x_4', 'x_5')
  eqns = eqns.replace('x_5', 'x_6')
  eqns = eqns.replace('x_6', 'x_7')
  eqns = eqns.replace('x_7', 'x_8')
  eqns = eqns.replace('x_8', 'x_9')

  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

'list' object has no attribute 'replace'

Run 4

import sympy

def sle(eqns):
  """
  This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
  """
  x = sympy.symbols('x')
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, x)) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('a_0x_0'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('a_1x_0'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('b_0x_1'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('b_1x_1'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('c0'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('c1'))[0]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('a_0x_0'))[1]) for eqn in eqns]
  eqns = [sympy.Eq(eqn, sympy.solve(eqn, sympy.symbols('a_1x_0'))[1]) for eqn in eqns]

  return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application

eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
                   (implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
        sides = [parse_expr(s, transformations=transformations)
                for s in eq.split('=')]
        parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]

result = True if list(sle(eqns).values()) == test_sol_values else False

Output:

Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)

spectral_r

Query

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  [insert]
  return sradius

Run 0

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.sum(a**2)


|/


  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

invalid syntax (<string>, line 11)

Run 1

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.sum(a**2)



  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 2

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.sum(a**2)



  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

Success

Run 3

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.sum(a**2)


|/ file dstars=0 



  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

invalid syntax (<string>, line 11)

Run 4

import numpy as np

def spectral_r(a):
  """
  This function calculates the spectral radius of the input square matrix a.
  """
  sradius = np.sum(a**2)


|/


  return sradius
import numpy as np

np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))

result = True if np.isclose(spectral_r(a), s_r) else False

Output:

invalid syntax (<string>, line 11)

find_peaks

Query

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    [insert]
    return wavenumbers

Run 0

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
    wavenumbers = [peak[0] for peak in peaks]



    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

`x` must be a 1-D array

Run 1

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
    peaks = np.asarray(peaks)
    wavenumbers = abs_spectrum[peaks, 0]



    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

`x` must be a 1-D array

Run 2

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
    peak_wavenumbers = [abs_spectrum[peak, 0] for peak in peaks]
    return peak_wavenumbers


    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

`x` must be a 1-D array

Run 3

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
    return peaks


    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

`x` must be a 1-D array

Run 4

import numpy as np
import scipy

import scipy.optimize
import scipy.signal

def find_peaks(abs_spectrum, npeaks=3):
    ''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
    `abs_spectrum` should be shape (N, 2)
    '''
    peak_positions, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
    peak_positions = np.array(peak_positions)
 0]
    peak_positions = peak_positions[peak_positions  len(abs_spectrum)-1]
 0]
    peak_positions = peak_positions[peak_positions  len(abs_spectrum)-1]
 0]
    return peak_positions


    return wavenumbers
s = np.loadtxt(
    'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))

true = [609, 645, 670]

result = len(ints) == 4
for t in true:
    result = result and np.any(np.abs(ints - t) < 5)

Output:

unindent does not match any outer indentation level (<string>, line 14)

speed_of_sound

Query

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   [insert]
   return s

Run 0

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   s = m*math.pow(T,gamma)


   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 1

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   s = m*T*math.exp(-gamma*T)



   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 2

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   s = gamma*T*m
   s += (T*m*math.exp(-gamma*T))
   
if __name__ == "__main__":
   T = int(sys.argv[1])
   m = float(sys.argv[2])
   gamma = float(sys.argv[3])
   print speed_of_sound(T,m,gamma)




   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

invalid syntax (<string>, line 17)

Run 3

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   s = T*m*gamma
   s = s*math.pow(10,-6)



   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

Run 4

import math
import sys

def speed_of_sound(T,m,gamma):
   """
   This function returns the speed of sound for an ideal gas at temperature T
   m is mass in g/mol
   """
   s = math.pow(T,m)/(gamma*math.pow(T,m))



   return s

import numpy as np

M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))

s_codex = speed_of_sound(T,M,gamma)

# check 
if np.isclose(s, s_codex, rtol=0.01) == True:
    result = True 
else:
    result = False

Output:

Success

substructure

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    [insert]
    return idx

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_list = Chem.MolFromSmiles(smiles)
    mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]

    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_list = Chem.MolFromSmiles(smiles)
    mol_list = [Chem.MolFromSmiles(x) for x in mol_list]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]
    mol_list = [x for x in mol_list if x is not None]

    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_list = Chem.MolFromSmiles(smiles)
    idxs = []
    for mol in mol_list:
        idx = mol_list.GetSubstructMatch(mol)
        idxs.append(idx)
    return idxs


    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_list = Chem.MolFromSmiles(smiles)
    mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
    mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]

    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def substructure(smiles, mol_list):
    """
    This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
    """
    mol_list = mol_list[:]
    mol_list.remove(smiles)
    mol_list = list(set(mol_list))
    idx = [i for i, x in enumerate(mol_list) if x == smiles]
    return idx


    return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
                                           'NCI', 'first_200.props.sdf')):
    idx = library.AddMol(mol)
    llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)

result = True if np.isclose(len(substructure(
    smiles, llibrary)), len(indices)) else False

Output:

File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf

tanimoto

Query

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  [insert]
  return s

Run 0

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  scaffold = Scaffolds.MolSSM(bits=bits)
  scaffold.Compute2DCoords()
  scaffold.SetProp("Compute2DCoords", True)
  scaffold.SetProp("MolWt", True)
  scaffold.SetProp("MolWtThreshold", 1e-6)
  scaffold.SetProp("MolWtMinVal", 1e-6)
  scaffold.SetProp("MolWtMaxVal", 1e-6)
  scaffold.SetProp("MolWtMinBias", 1e-6)
  scaffold.SetProp("MolWtMaxBias", 1e-6)
  scaffold.SetProp("MolWtMaxIter", 1000)
  scaffold.SetProp("MolWtMaxIterMax", 1000)
  scaffold.SetProp("MolWtMaxIterMin", 1000)
  scaffold.SetProp("MolWtMinBias", 1e-6)
  scaffold.SetProp("MolWtMaxBias", 1e-6)
  scaffold.SetProp("MolWtMaxIter", 1000)

  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MolSSM'

Run 1

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  scaffold = Scaffolds.MurckoScaffold()
  scaffold.Compute2DCoords()
  scaffold.Compute2DCoords(useFeatures=True)
  scaffold.Compute2DCoords(useFeatures=False)
  scaffold.SetProp("Compute2DCoords", True)
  scaffold.SetProp("MurckoPhi", True)
  scaffold.SetProp("MurckoPhiBits", bits)
  scaffold.SetProp("MurckoPhiRadius", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)
  scaffold.SetProp("MurckoPhiRadiusBits", bits)

  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

Run 2

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  scaffold = Scaffolds.MurckoScaffold()
  scaffold.Compute2DCoords()
  scaffold.SetProp("Compute2DCoords", True)
  scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponent", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponentBias", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponentBiasExponent", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponentBiasExponentBias", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponentBiasExponentBiasExponent", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsExponentBiasExponentBiasExponentBiasExponent", bits)

  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

Run 3

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  scaffold = Scaffolds.MurckoScaffold()
  scaffold.SetProp("MurckoScaffold.NumBits", bits)
  scaffold.SetProp("MurckoScaffold.NumExpBits", bits)
  scaffold.SetProp("MurckoScaffold.NumRadicalElectrons", bits)
  scaffold.SetProp("MurckoScaffold.NumRadicalHs", bits)
  scaffold.SetProp("MurckoScaffold.NumRotatableBonds", bits)
  scaffold.SetProp("MurckoScaffold.NumExplicitHs", bits)
  scaffold.SetProp("MurckoScaffold.NumImplicitHs", bits)
  scaffold.SetProp("MurckoScaffold.NumRotatableBonds", bits)
  scaffold.SetProp("MurckoScaffold.NumExplicitHs", bits)
  scaffold.SetProp("MurckoScaffold.NumImplicitHs", bits)

  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

Run 4

import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np

def tanimoto_matrix(smiles_list, bits=256):
  """
  Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
  """
  scaffold = Scaffolds.MurckoScaffold()
  scaffold.Compute2DCoords()
  scaffold.SetProp("Compute2DCoords", True)
  scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsError", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsWarning", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracy", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyError", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyWarning", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracy", bits)
  scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracyError", bits)

  return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools


def ref_tan_matrix(slist):
    fp = [AllChem.GetMorganFingerprintAsBitVect(
        Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
    ts = list(
        TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
    )
    return np.array(ts).reshape(len(fp), len(fp))


mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
        'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
    mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else False

Output:

module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'

unbdistance

Query

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    [insert]
    return result

Run 0

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_traj = md.load(lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')
    lig_traj = lig_traj.select('resname'+ lig_str + '*')

    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 1

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_str_residue = lig_str[lig_str.find('_')+1:]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')
    lig_str_residue = lig_str_residue[0]
    lig_str_residue = lig_str_residue.split('_')

    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 2

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_traj = md.load(lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str +' resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str)
    lig_traj = lig_traj.select('resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str +' resname'+ lig_str)

    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 3

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_traj = md.load(lig_str)
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()
    lig_traj.save("lig_traj")
    lig_traj = md.load("lig_traj")
    lig_traj.compute_center_of_mass()

    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

Run 4

import mdtraj as md
import numpy as np

def unbdistance(traj,lig_str):
    """
    This function returns a list of distances between center of mass of
    protein and center of mass of lig_str in every frame of trajectory
    traj

    traj is an mdtraj trajectory object
    lig_str is a string with the residue name of the ligand
    """
    lig_traj = traj[lig_str]
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')
    lig_traj = lig_traj.select('resname LIG')

    return result
import mdtraj as md
import os
import math
import numpy as np


#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd') 
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)

dist = []
for i,j in zip(traj2,traj3):
    com_a = md.compute_center_of_mass(i)[0]
    com_b = md.compute_center_of_mass(j)[0]
    dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)

# assert

distances = unbdistance(traj,lig_str)

check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False 

Output:

'Constant' object has no attribute 'kind'

velocity_verlet_integration

Query

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    [insert]
    return x_traj, v_traj

Run 0

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v_traj[i-1])
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v_traj[i-1])



    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

F() takes from 1 to 2 positional arguments but 3 were given

Run 1

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)*dt
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)*dt*dt
    



    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

F() takes from 1 to 2 positional arguments but 3 were given

Run 2

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + F(x_traj[i-1], v_traj[i-1], v0) * dt
        v_traj[i] = v_traj[i-1] + F(x_traj[i-1], v_traj[i-1], v0) * dt



    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

F() takes from 1 to 2 positional arguments but 3 were given

Run 3

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + F*dt*v_traj[i-1]
        v_traj[i] = v_traj[i-1] + F*dt*x_traj[i-1]
    



    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

unsupported operand type(s) for *: 'function' and 'float'

Run 4

import numpy as np

def verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    Integrates given force field with Velocity-Verlet integration
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    
    x_traj[0] = x0
    v_traj[0] = v0
    
    for i in range(1, steps):
        x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)
        v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1], v_traj[i-1], v0) + dt*F(x_traj[i-1], v_traj[i-1], v0)



    return x_traj, v_traj
import numpy as np


def ref_verlet_integrate(x0, v0, F, steps=1000, dt=0.001):
    """
    This function runs velocity verlet integration with the given force function F.
    """
    x_traj = np.zeros(steps)
    v_traj = np.zeros(steps)
    x_traj[0] = x0
    v_traj[0] = v0
    for i in range(steps-1):
        v = v_traj[i] + 0.5 * F(x_traj[i]) * dt
        x_traj[i+1] = x_traj[i] + v * dt
        v_traj[i+1] = v + 0.5 * F(x_traj[i+1])*dt
    return x_traj, v_traj


def F(q, k=2):
    return -k*q


def U(q, k=2):
    return 0.5 * k*q**2


x_traj, v_traj = verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
xr_traj, vr_traj = ref_verlet_integrate(0.1, -0.1, F, 100000, dt=1e-3)
result = np.allclose(x_traj, xr_traj) and np.allclose(v_traj, vr_traj)

Output:

F() takes from 1 to 2 positional arguments but 3 were given